位置: 编程技术 - 正文

cordova JS和HTML页面的数据通信(javascriptweb)

编辑:rootadmin

推荐整理分享cordova JS和HTML页面的数据通信(javascriptweb),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:cordova webview,html javascript页面,javascript webgl,javascriptweb,javascript document,javascriptweb,javascriptweb,jswebcontrol,内容如对您有帮助,希望把文章链接给更多的朋友!

项目下载地址: 不断摸索,才找到这个通过插件的方法实现通信

在5.0版本中,不再使用jar包的形式,我们如果要建立一个项目,需要通过命令行来新建(在此之前要先把环境配置好,详情请参见 create MyPluginTest com.example.myplugintest MyPluginTest

cd MyPluginTest

我在这里添加了几个插件

下面是添加平台

cordova platform add android

由于我是使用eclipse来开发的,所以build这一步我就不再使用命令行了,而是等下用eclipse直接运行就好了。

所以执行完上面这些命令后,把生成的这个项目导入到eclipse中,就是一个最基本的helloworld了。

导入后可以看到项目是这个样子的,如果你从windows打开项目,你会看到assets文件夹里面包含www文件夹,里面放着各个html和js文件的。但是在eclipse中却发现assets文件夹里面没有www文件夹,这是怎么回事呢?其实是因为它被隐藏了,在这里我觉得没必要非让它显示出来,毕竟这是cordova不希望你看到的。再来看看,项目的根目录下面有一个www文件夹,其实如果我们要编辑html,js文件,是可以对它进行操作的,在这个www文件夹下找到index.html进行修改即可。

但是有一点要注意,您应该也注意到了www文件夹有一个类&#;快捷方式一样的小图标,这说明我们直接对该文件夹内的文件的修改并不能直接应用到assets/www文件夹内的,在修改完后,我们还需要在命令行中去到项目的根目录中运行命令

运行这个命令后,再在eclipse中运行,这样html文件的修改才可以改成功,否则你会发现不论你怎么改,页面都不会有变化的

在了解正确修改html的做法后,我们继续来完成数据通信的功能吧

生成的项目会在src下面的com.example.myplugintest包生成一个MainActivity,这个activity里面的内容基本就是载入页面。在这里,我们需要对原来部分进行一系列修改。在demo中,程序的启动activity是FirstActivity,然后点击按钮可以去到MainActivity,在MainActivity里载入HTML页面,通过页面的按钮点击可以去到SecondActivity。所以我们还需要在配置文件中把启动activity给更改掉。

AndroidManifest.xml

<?xml version='1.0' encoding='utf-8'?><manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="com.example.myplugintest" xmlns:android=" <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <application android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name" android:supportsRtl="true"> <activity android:launchMode="standard" android:name="MainActivity" android:theme="@android:style/Theme.Black.NoTitleBar" android:windowSoftInputMode="adjustResize"> </activity> <activity android:name="FirstActivity" android:launchMode="standard"> <intent-filter android:label="@string/launcher_name"> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="SecondActivity" android:launchMode="standard"/> </application> <uses-sdk android:minSdkVersion="" android:targetSdkVersion="" /></manifest>

在com.example.myplugintest包新建2个activity

注意,在新建的时候,如果直接右键新建android activity,建立完成后可能由于和cordova的冲突项目会报错,所以我只好新建一个类,再让那个类继承Activity(也就是以手工的方式来写),然后再去新建布局文件什么的。

FirstActivity.java

package com.example.myplugintest;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.KeyEvent;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class FirstActivity extends Activity{TextView tvTitle;EditText etContent;Button btnSend;public static FirstActivity firstActivity ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_first);firstActivity = this;tvTitle = (TextView)findViewById(R.id.tvTitle);tvTitle.setOnClickListener(new OnClickListener(){ @Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubIntent intent = new Intent(FirstActivity.this,MainActivity.class);startActivity(intent); }});etContent = (EditText)findViewById(R.id.etContent);btnSend = (Button)findViewById(R.id.btnSend);btnSend.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubString text = etContent.getText().toString();Intent intent = new Intent(FirstActivity.this,MainActivity.class);intent.putExtra("data", text);startActivity(intent);}});Intent intent = getIntent();if(intent != null){String title = intent.getStringExtra("title");tvTitle.setText(title);}}public String getMessage(){return this.etContent.getText().toString();}public void changeText(String text){tvTitle.setText("i'm the first activity , my text change to :"&#;text);}}

在res/layout 文件夹下面建立其对应的布局文件 activity_first.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@&#;id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="i'm the first activity"/> <EditText android:id="@&#;id/etContent" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@&#;id/btnSend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="把文本框的&#;赋&#;给HTML页面"/></LinearLayout>

cordova JS和HTML页面的数据通信(javascriptweb)

SecondActivity.java

package com.example.myplugintest;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.KeyEvent;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class SecondActivity extends Activity{TextView tvTitle;EditText etContent;Button btnSend;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_second);tvTitle = (TextView)findViewById(R.id.tvTitle);String title = getIntent().getStringExtra("title");tvTitle.setText(title);etContent = (EditText)findViewById(R.id.etContent);btnSend = (Button)findViewById(R.id.btnSend);btnSend.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubString text = etContent.getText().toString();Intent intent = new Intent ();intent.putExtra("data", text);setResult(,intent);finish();}});}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_BACK) {Intent intent = new Intent ();intent.putExtra("data", "data from second activity");// Toast.makeText(this, "onkeydown", 0).show();setResult(,intent);finish();}return super.onKeyDown(keyCode, event);}}

对应的布局文件activity_second.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@&#;id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="no data"/> <EditText android:id="@&#;id/etContent" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@&#;id/btnSend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="把文本框的&#;赋&#;给HTML页面"/> </LinearLayout>

然后MainActiviy.java改成这样

package com.example.myplugintest;import android.content.Intent;import android.os.Bundle;import org.apache.cordova.*;public class MainActivity extends CordovaActivity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set by <content src="index.html" /> in config.xml Intent intent = getIntent(); String data = intent.getStringExtra("data"); loadUrl(launchUrl); }}

添加我们的插件CalendarPlugin.java到com.example.myplugintest

CalendarPlugin.java

package com.example.myplugintest; import org.apache.cordova.CallbackContext;import org.apache.cordova.CordovaPlugin;import org.json.JSONObject;import org.json.JSONArray;import org.json.JSONException;import android.app.Activity; import android.content.Intent;import android.util.Log;import android.widget.Toast;public class CalendarPlugin extends CordovaPlugin {public static final String ACTION_FIRST = "action first"; public static final String ACTION_SECOND = "action second"; public static final String ACTION_THIRD = "action third"; public CallbackContext callbackContext; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { try { if (ACTION_SECOND.equals(action)) { this.callbackContext = callbackContext; JSONObject arg_object = args.getJSONObject(0);// Intent calIntent = new Intent(Intent.ACTION_EDIT)// .setType("vnd.android.cursor.item/event")// .putExtra("beginTime", arg_object.getLong("startTimeMillis"))// .putExtra("endTime", arg_object.getLong("endTimeMillis"))// .putExtra("title", arg_object.getString("title"))// .putExtra("description", arg_object.getString("description"))// .putExtra("eventLocation", arg_object.getString("eventLocation"));// // this.cordova.getActivity().startActivity(calIntent); String title = arg_object.getString("title"); Intent intent = new Intent(cordova.getActivity(), SecondActivity.class); intent.putExtra("title",title); cordova.startActivityForResult((CordovaPlugin) this,intent, ); return true; } else if(ACTION_FIRST.equals(action)) {this.callbackContext = callbackContext; JSONObject arg_object = args.getJSONObject(0); String title = arg_object.getString("title"); Intent intent = new Intent(cordova.getActivity(), FirstActivity.class); intent.putExtra("title",title); cordova.startActivityForResult((CordovaPlugin) this,intent, ); return true; } else if(ACTION_THIRD.equals(action)) {this.callbackContext = callbackContext; String message = FirstActivity.firstActivity.getMessage(); callbackContext.success(message); return true; } callbackContext.error("Invalid action"); return false; } catch(Exception e) { System.err.println("Exception: " &#; e.getMessage()); callbackContext.error(e.getMessage()); return false; } } @Overridepublic void onActivityResult(int requestCode, int resultCode, Intent intent) {super.onActivityResult(requestCode, resultCode, intent);if(intent == null) return;//传递返回&#; 给js方法String data = intent.getStringExtra("data");callbackContext.success(data);} }

修改www文件夹下的index.html文件

index.html

<!DOCTYPE html><!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.--><html> <head> <!-- Customize this policy to fit your own app's needs. For more guidance, see: Some notes: * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication * is required only on Android and is needed for TalkBack to function properly * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: * Enable inline JS: add 'unsafe-inline' to default-src --> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>Hello World</title> </head> <body> <p id="showText">text</p> <input id="ipContent" type="text">请输入内容 </input> <input id="ipGoFirst" type="button" value="把文本框内容赋&#;给第一个activity" onclick="goToFirst()"></input> <p/> <input id="ipGoSecond" type="button" value="把文本框内容赋&#;给第二个activity" onclick="goToSecond()"></input> <div class="app"> <h1>Apache Cordova</h1> <div id="deviceready" class="blink"> <p class="event listening">Connecting to Device</p> <p class="event received">Device is Ready</p> </div> </div> <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript" src="js/calendar.js"></script> <script type="text/javascript" > function goToFirst() { var a = document.getElementById("ipContent").value; var startDate = new Date("July , 8::"); var endDate = new Date("July , ::"); var notes = "Arrive on time, don't want to miss out (from Android)"; var title = a; var location = "action first"; var notes = "Arrive on time, don't want to miss out!"; var success = function(message) { alert("Success"&#;message); changeText(message); }; var error = function(message) { alert("Oopsie! " &#; message); }; calendarPlugin.createEvent(title, location, notes, startDate, endDate, success, error); } function goToSecond() { var a = document.getElementById("ipContent").value; var startDate = new Date("July , 8::"); var endDate = new Date("July , ::"); var notes = "Arrive on time, don't want to miss out (from Android)"; var title = a; var location = "action second"; var notes = "Arrive on time, don't want to miss out!"; var success = function(message) { alert("Success"&#;message); changeText(message); }; var error = function(message) { alert("Oopsie! " &#; message); }; calendarPlugin.createEvent(title, location, notes, startDate, endDate, success, error); } function changeText(message) { document.getElementById("showText").innerHTML = message; } function goToThird() { var a = document.getElementById("ipContent").value; var startDate = new Date("July , 8::"); var endDate = new Date("July , ::"); var notes = "Arrive on time, don't want to miss out (from Android)"; var title = a; var location = "action third"; var notes = "Arrive on time, don't want to miss out!"; var success = function(message) { alert("Success"&#;message); changeText(message); }; var error = function(message) { alert("Oopsie! " &#; message); }; calendarPlugin.createEvent(title, location, notes, startDate, endDate, success, error); } function addLoadEvent(func){ var oldonload = window.onload; if (typeof window.onload != 'function'){ window.onload = func; } else { window.onload = function(){ oldonload(); func(); } } } addLoadEvent(goToThird); </script> </body></html>

在www/js文件夹下面添加插件的js文件

calendar.js

var calendarPlugin = { createEvent: function(title, location, notes, startDate, endDate, successCallback, errorCallback) { cordova.exec( successCallback, // success callback function errorCallback, // error callback function 'CalendarPlugin', // mapped to our native Java class called "CalendarPlugin" location, // with this action name [{ // and this array of custom arguments to create our entry "title": title, "description": notes, "eventLocation": location, "startTimeMillis": startDate.getTime(), "endTimeMillis": endDate.getTime() }] ); }}

最后一步是在config.xml文件中把关于插件的信息添加进去

config.xml

<?xml version='1.0' encoding='utf-8'?><widget id="com.example.myplugintest" version="0.0.1" xmlns=" xmlns:cdv=" <preference name="loglevel" value="DEBUG" /> <feature name="Whitelist"> <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" /> <param name="onload" value="true" /> </feature> <feature name="Device"> <param name="android-package" value="org.apache.cordova.device.Device" /> </feature> <feature name="CalendarPlugin"> <param name="android-package" value="com.example.myplugintest.CalendarPlugin" /> </feature><allow-intent href="market:*" /> <name>MyPluginTest</name> <description> A sample Apache Cordova application that responds to the deviceready event. </description> <author email="dev@cordova.apache.org" href=" Apache Cordova Team </author> <content src="index.html" /> <access origin="*" /> <allow-intent href=" /> <allow-intent href=" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" /></widget>

但是很奇怪的一点是,如果直接在eclipse项目中修改config.xml文件,等会再运行prepare命令,却发现config.xml文件又重置回来了

所以我是直接在windows中找到D:eclipseadteclipsemyWorkspaceMyPluginTestplatformsandroidresxmlconfig.xml,直接对其进行修改的。

操作顺序应该是这样的:修改www文件夹的内容 - 执行prepare命令 - 在windows中通过写字板方式修改config.xml - 在eclipse中运行

————————————————————————————————————————————————————

按照上面的操作,demo项目就完成了,在eclipse中运行可以看到效果。

android icon和启动页大小与尺寸 1.本人根据经验记录下来的,属于保存,不好之处勿喷icon四个尺寸*(2k),*(3k),*(4k),*(5..5k)png启动页类网页启动页,尺寸一个

Sub-process /usr/bin/dpkg returned an error code (1)错误解决办法 这几天用ubuntu.,在用apt-get安装软件时出现了类于:install-info:Nodirfilespecified;try--helpformoreinformation.dpkg:处理gettext(--configure)时出错:子进程post-install

Android--全局获取Context的技巧 Android中很多地方都会用到Context,弹出Toast的时候需要、启动活动时需要、发送广播的时候也需要、操作数据库的时候需要、使用通知的时候也需要等等

标签: javascriptweb

本文链接地址:https://www.jiuchutong.com/biancheng/378191.html 转载请保留说明!

上一篇:listview中嵌套子listview,解决子listview点击问题(list嵌套list采用什么结构)

下一篇:android icon和启动页大小与尺寸(安卓手机如何打开.icon文件)

  • 小规模销售收入要做销项税额吗
  • 企业分红缴纳所得税
  • 公司取得违约金合法吗
  • 工程咨询属于什么合同
  • 增值税专用发票可以开电子发票吗
  • 不动产什么时候可以抵扣进项税额
  • 资产减值损失属于什么科目借方增加还是减少
  • 出口旧设备最新政策
  • 国有独资企业董事会应当在每年
  • 预收保费属于什么会计科目类别
  • 员工奖金分两次发怎么交税?
  • 公司的样品一般怎么处理
  • 预收账款缴税的计算公式
  • 哪些发票不可进行进项税抵扣?
  • 营改增后混合销售的规定
  • 工程交税需要什么资料
  • 燃油税改革了谁的钱包
  • 公司为员工需要承担哪些责任
  • 异地工程需要预交税吗
  • 企业的经济成本由什么构成
  • 单位汽车按揭贷款怎么贷
  • 学校收取食堂管理费
  • 电子发票跨月怎么开红字发票
  • 往来款项分为哪两类
  • 亏损企业季度盈利企业所得税怎么预缴?
  • 银行承兑电子汇票到期要怎么操作
  • 购买商品接受劳务的现金流包括哪些
  • 产品试用装怎么做会计分录
  • Win10 Version 1909累积更新补丁KB4601315:修复诸多 BUG
  • win10的病毒隔离有用吗
  • 圣伊利亚斯山
  • 安保费差额纳税是什么意思
  • 注销公司如何登报
  • 注销公司如何注销
  • 业务招待费税前扣除标准按照发生额的60%扣除
  • 自定义修改器
  • php制作数字验证码
  • 委托贷款会计处理流程
  • 利润分配的账务处理如何做
  • 圣克鲁斯河特点
  • 企业收到对外投资收益交所得税吗
  • 梵净山原名
  • 西部大开发的主要政策措施是什么?
  • vuex中this.$store.commit和this.$store.dispatch的用法
  • 共享主机和vps
  • python查看type
  • find命令详解查找文件
  • 小规模纳税人怎么开专票
  • 编制利润表计算公式
  • 金蝶专业版数量金额明细账设置
  • 什么是全面一次性奖金
  • 股权转让产生的个人所得税
  • 企业哪些情况下需要交税
  • 房地产企业简易计税和一般计税的区别
  • 付别人押金的会计分录
  • 固定资产房屋拆除后如何做帐务处理
  • 买车能不交税吗
  • 退货开负数发票的情况该如何做会计处理?
  • 工会经费计提按照应发工资还是实发工资
  • 企业盘亏的设备会计分录
  • 外经证预交税款可以以后月份抵扣吗
  • 资产类科目一般是什么
  • 生育津贴案件
  • sqlserver增删改查执行语句
  • win7出现蓝屏如何解决
  • 运行方式包括什么方式
  • win7小键盘数字键不能用怎么办
  • win81蓝屏重启故障
  • kernel headers not found for target kernel
  • ftp下载怎么用
  • 网页设计css文字居中
  • javascript教程chm
  • 省市区三级联动下拉表单
  • 详解HTTPS 的原理和 NodeJS 的实现
  • 基于python的研究
  • javascript如何学
  • 德州市税务局领导
  • 西安市地方税务局高新技术产业开发区分局
  • 汽车燃油税每年要交吗
  • 房屋租赁税房东不承担怎么办理
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设