android + javascript 相互通信


参考博客:
android + javascript 相互通信实例分析
http://www.cnblogs.com/yaozhongxiao/p/3408948.html


这次要做的事情是:在应用中载入网页,通过javascript与应用程序相互通信。


准备工作:
先弄个网页,效果如下

网页代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script language="javascript">
        function wave(img) {
            if (confirm("确认领取优惠券?")) {
	            img.src="android_waving.png";
	            var id=img.id;
	            // alert(id);
	            window.demo.clickOnAndroid(id);
        	};
        }
    </script>
</head>
    <body>
        <!-- Calls into the javascript interface for the activity -->
        <div>
                <img onClick="wave(this)" id="3" src="3.jpg" width="200" height="100"/><br>
        </div>
        <div>
                <img onClick="wave(this)" id="10" src="10.jpg" width="200" height="100"/><br>
        </div>
        <div>
                <img onClick="wave(this)" id="100" src="100.jpg" width="200" height="100"/><br>
        </div>
        
    </body>
</html>

window.demo.clickOnAndroid(id)
这个js方法不会执行,他的作用请看下文


再弄个webview,不多说
	WebView mWebView = (WebView) view.findViewById(R.id.webView);
        WebSettings webSettings = mWebView.getSettings();
//        webSettings.setSavePassword(false);
//        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);
//        webSettings.setSupportZoom(false);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
        mWebView.loadUrl("file:///android_asset/demo.html");


mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
这行代码的作用,下文解释。


将网页扔到这个文件夹下

注意!有些js方法少了jquery.js不会执行,会报错


在MyWebChromeClient中重写Confirm:
    final class MyWebChromeClient extends WebChromeClient {
        @Override
		public boolean onJsConfirm(WebView view, String url,
				String message, final JsResult result) {
			// TODO Auto-generated method stub
        	Builder builder=new Builder(getActivity());
        	builder.setTitle("领取优惠券");
        	builder.setMessage(message);
        	builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					result.confirm();
				}
			});
        	builder.setNeutralButton(android.R.string.cancel, new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					result.cancel();
				}
			});
        	builder.setCancelable(false);
        	builder.create();
        	builder.show();
            return true;
		}
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            result.confirm();
            return true;
        }
    }


这样,当执行js中
confirm("确认领取优惠券?")
这个方法的时候
就会执行onJsConfirm()


显然实现到这个地步,距离我们的目标还有一段距离。
现在我要点击这个图片之后,发送一个广播,并且将这个图片的id记录到数据库中。


网页中只需要添加一行代码,就是上文提到的这行:window.demo.clickOnAndroid(id);

然后webview中添加js接口,也是上文提到的这行:mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");


最后实现接口:
final class DemoJavaScriptInterface {
    DemoJavaScriptInterface() {
    }
    /**
     * This is not called on the UI thread. Post a runnable to invoke
     * loadUrl on the UI thread.
     */
    public void clickOnAndroid(final String id) {
        mHandler.post(new Runnable() {
            public void run() {
				//mWebView.loadUrl("javascript:d()");
            	// 发送自定义广播
        		Intent broadcast=new Intent("android.example.YOUHUI");
    			//实例化bundle,设置需要传递的参数
    			Bundle bundle=new Bundle();
    			bundle.putString("id", id);
    			
    			//	将参数传递给intent对象
    			broadcast.putExtras(bundle);
        		getActivity().sendBroadcast(broadcast);
				//Log.i("MyLog", id);       		
        		Intent intent=new Intent(getActivity(), MyPreferential.class);
    			//	将参数传递给intent对象
    			intent.putExtras(bundle);
				startActivity(intent);
            }
        });
    }
}




好了我发送了一个自定义广播android.example.YOUHUI,而且将id传递了过去
在manifest中配置广播接收器
<receiver android:name="com.example.broadcast.NotifRece">
    <intent-filter>
        <action android:name="android.example.YOUHUI"/>
    </intent-filter>
</receiver>

public class NotifRece extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		NotificationManager notif=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification note=new Notification(R.drawable.ic_launcher,"恭喜你成功领取优惠券!",System.currentTimeMillis());
		Intent i=new Intent(context,MyPreferential.class);
		
		Bundle bundle=intent.getExtras();
		if (null!=bundle&&null!=bundle.getString("id")) {
			i.putExtra("id", bundle);
		}
		
		PendingIntent pi=PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
		note.setLatestEventInfo(context, "成功领取优惠券","点击查看我的优惠券", pi);
		notif.notify(1, note);
	}
}


在MyPreferential这个活动中,中将数据写入数据库:

public class MyPreferential extends Activity  {
	TextView textView;
	private DatabaseHelper dbHelper;
	
	private static final String DATABASE_NAME = "db.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "employee";
	
	@Override
	protected void onCreate(Bundle savedInstanceState)	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_preferential);
		
		dbHelper= new DatabaseHelper(this, DATABASE_NAME, null, DATABASE_VERSION);
		textView=(TextView) this.findViewById(R.id.result);
		textView.setText("id			属性				金额 \n");
		CreateTable();
		
		NotificationManager notif=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		
		Intent intent=this.getIntent();
		Bundle bundle=intent.getExtras();
		if (null!=bundle&&null!=bundle.getString("id")) {
			String id = bundle.getString("id");
			insertItem(id);
		}else {
			notif.cancel(1);
		}		
		showItems();
	}
	
	 // 创建数据表
    private void CreateTable() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME
                + " (ID INTEGER PRIMARY KEY, Name VARCHAR, Age VARCHAR);";
        try {
            db.execSQL(sql);
            Log.i("sql", "数据表成功创建");
        } catch (SQLException ex) {
            Log.e("sql", "数据表创建错误");
        }
    }

    // 插入数据
    private void insertItem(String id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        
        try {
            Random random = new Random();
            String sql = "insert into " + TABLE_NAME
                    + " (name, age) values ('优惠券', " + id + ")";
            // execSQL() - 执行指定的 sql
            db.execSQL(sql);
        } catch (SQLException ex) {
        	Log.e("sql", "插入数据错误");
        }
    }
    
    // 删除数据
    public void deleteItem(View view) {
        try {
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            db.delete(TABLE_NAME, " id < 999999", null);
            textView.setText("id		属性		金额 \n");
            Log.i("sql", "delete success");
        } catch (SQLException e) {
        }
    }

    // 查询数据
    private void showItems() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        try {
            String[] column = { "id", "name", "age" };
            Cursor cursor = db.query(TABLE_NAME, column, null, null, null,
                    null, null);
            Integer num = cursor.getCount();
            cursor.moveToFirst();

            while (cursor.getPosition() != cursor.getCount()) {
            	textView.append(String.valueOf(cursor.getString(0)) + "		"
                        + cursor.getString(1) + "		"
                        + String.valueOf(cursor.getString(2)) + "\n");
                cursor.moveToNext();
            }
        } catch (SQLException ex) {
        	Log.e("sql", "查询数据错误");
        }
    }
    
}

运行效果:




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值