andorid利用webview实现java和js交互

42 篇文章 0 订阅

这里写的一个小例子是这样的,点击移动按钮然后hello wold就会移动,点击停止就会停止,逻辑操作是在js里面然后界面更新是java,我们先来看看这样效果。

这里我们先写好布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/move"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onclick"
        android:text="移动" />

    <Button
        android:id="@+id/end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/move"
        android:onClick="onclick"
        android:text="停止" />

</RelativeLayout>

然后写好我们js代码,在res文件夹下面新建raw文件夹,在这里面我们写两个js文件给出这两个js的代码。首先是start.js的代码。
<script language="javascript">

var timer;
function startTimer()
{
	//使用定时器2m调用一次
	timer = setInterval("randomMoveButton()",2000);
}
//定时器函数
function randomMoveButton()
{
	var x = Math.round(Math.random()*300);
	var y = Math.round(Math.random()*300+100);
	window.demo.move(x,y);
}
//开始定时器
startTimer();
</script>

然后是end.js的代码

<script language="javascript">
//移除定时器
clearInterval(timer);
</script>

最后给出我们的activity代码

public class MainActivity extends Activity {

	private String startjs;//开始的js代码
	private String endjs;//结束的js代码
	private WebView webView;
	private TextView textView;
	//在hander中更新textview的位置
	Handler handler = new Handler() {

		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			int x = msg.arg1;
			int y = msg.arg2;
			textView.layout(x, y, textView.getMeasuredWidth() + x, textView.getMeasuredHeight() + y);
			super.dispatchMessage(msg);
		}

	};

	@SuppressLint("JavascriptInterface")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView) findViewById(R.id.textview);
		webView = new WebView(this);
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);//打开js支持
		//这里添加js的调用的接口 它的调用都是通过这个Object类传递
		webView.addJavascriptInterface(new Object() {
			//这个是js里面调用的方法
			public void move(int x, int y) {
				Message message = new Message();
				message.arg1 = x;
				message.arg2 = y;
				handler.sendMessage(message);
			}
		}, "demo");
		startjs = getjs(getResources().openRawResource(R.raw.start));
		endjs = getjs(getResources().openRawResource(R.raw.end));

	}

	//获取js代码
	private String getjs(InputStream inputStream) {
		byte[] buffer = new byte[1024];
		String js = null;
		int len = 0;
		try {
			len = inputStream.read(buffer);
			js = new String(buffer, 0, len, "utf-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return js;
	}
	public void onclick(View view) {
		switch (view.getId()) {
		case R.id.move:
			webView.loadDataWithBaseURL(null, startjs, "text/html","utf-8", null);
			break;
		case R.id.end:
			webView.loadDataWithBaseURL(null, endjs, "text/html","utf-8", null);
			break;
		default:
			break;
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值