Android 和 ios都能够和javascript交互了!!!

本文介绍如何在手机应用中结合网页与nativecode进行交互,通过使用webview组件并设置JavaScript支持,实现从网页到nativecode的调用与响应。详细展示了Android与iOS平台的具体操作步骤及代码实现。

        在手机开发中,我们往往会碰到结合网页的任务,不管怎么说,网页做出的效果比原生的code总是要好得多,怎么样将网页中的javascript结合我们的native方法使用呢?不管是Android还是ios都集成了对Javascript的支持。


        主页面代码:

       

/**
 * 
 */
package com.qzf.webviewtest;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * @author Administrator
 *
 */
public class MainActivity extends Activity {
	
	private ListView listView1;
	private ListAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		/**
		 * 强制设置为竖屏
		 */
		if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		}
		setContentView(R.layout.main);
		final String packName = getPackageName();
		listView1 = (ListView)findViewById(R.id.listView1);
		String [] items = new String[] {"WebTest1", "WebTest3Image"};
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); 
		listView1.setAdapter(adapter);
		listView1.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					Class<?> clazz = Class.forName(packName + "." + (String) parent.getAdapter().getItem(position));
					startActivity(new Intent(getApplicationContext(), clazz));
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
			
		});
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}

主页面布局main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:divider="@android:color/black"
        android:dividerHeight="5dp"
        android:background="#f0f0f0">
    </ListView>
    
    <View android:layout_height="5dp"
        android:background="@android:color/black"
        android:layout_width="match_parent"/>

</LinearLayout>


        1、在Android中javascript与native code交互

        结合网页首先要使用到webview这个组件,首先得到webview对象之后,我们需要调用webview.setJavaScriptEnabled(bool)这个方法,告知Android系统我们需要使用到javascript的支持,然后加载网页,加载完之后调用webview.addJavascriptInterface(obj, methodName);方法给webview加上插件,这个插件里面实现我们要执行的方法即可,下面是代码。

       

package com.qzf.webviewtest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;

@SuppressLint("SetJavaScriptEnabled")
public class WebTest1 extends Activity {
	private WebView webView1 = null;
	private LinearLayout nav1 = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		/**
		 * 强制设置为竖屏
		 */
		if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		}
		setContentView(R.layout.webtest1);
		webView1 = (WebView)findViewById(R.id.webView1);
		nav1 = (LinearLayout)findViewById(R.id.nav1);
		WebSettings wset = webView1.getSettings();
		wset.setJavaScriptCanOpenWindowsAutomatically(true);
		wset.setJavaScriptEnabled(true);
		webView1.loadUrl("file:///android_asset/demo1.html");//加载本地assets中的html
		webView1.addJavascriptInterface(new JavaScriptObject(), "test1");
  		nav1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new Handler().post(new Runnable() {

					@Override
					public void run() {//当点击上面的layout时调用javascript中的setContentInfo方法
						webView1.loadUrl("javascript:setContentInfo('Hello Native Code.')");
					}
				});
			}
		});
	}
	
	class JavaScriptObject {

		@JavascriptInterface
		public void goCDetail() throws Exception {
			finish();//这里简单的使用js调用Android中返回的方法
		}
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
这里是布局文件webtest1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/nav1"
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:background="#268525"
        android:layout_height="50dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:text="请点击这里设置文本框数据" />
    </LinearLayout>

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>



这里是demo1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Android嵌入web页面</title>

<script type="text/javascript">
	function setContentInfo(object){
		var txt1 = document.getElementById("txt1");
		txt1.value = object;
	}
</script>
</head>
<body>
	<p>Android嵌入web页面.</p>
	<input type="button" value="调用Android操作系统版本" onclick="javascript:test1.goCDetail();"/><br/>
	<input type="button" value="调用Android操作系统版本" onclick="setContentInfo('Hello');"/><br/>
	<input id="txt1" type="text" value="等待输入"/>	
</body>
</html>
2.ios中与native code交互

网页中的代码都是不变的,只是调用的方式上可能Android的更加灵活一些,ios如果想用js调用native只能是在shouldStartLoadWithRequest这个方法中对js发来的指令进行处理,这里只有windows系统,就不贴方法了,基本上原理都一样的,shouldStartLoadWithRequest是能够获取到所有的网页中传递出来的请求的,所以根据自定义的协议,完全可以做到任何事买外,这个只能够单向处理,想要回传,就需要使用stringByEvaluatingJavaScriptFromString这个方法去掉用指定的javascript方法了,调用方式与Java差不多,有需要的童鞋可以试一下,哈哈,以后就可以肆无忌惮的使用html结合手机app啦!

点击上方的大按钮之后


点击网页中第二个按钮

点击网页中第一个按钮就可以退出页面了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值