您的位置:首页 > 移动开发 > Android开发

android java与webview中js交互

2016-11-08 11:30 399 查看
问题描述:在点击webview上按钮时,响应activity中定义的事件

需求:点击webview上的按钮,传url到过来,Android跳转到另外的activity页面

一、xml代码

<LinearLayout 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:orientation="vertical"
>

<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

</LinearLayout>


二、activity代码

package com.example.webviewtest;

import android.os.Bundle;
import android.os.Handler;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

private WebView webview;

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" }) @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);

WebSettings webSettings = webview.getSettings();
//设置WebView属性,能够执行Javascript脚本
webSettings.setJavaScriptEnabled(true);
//设置可以访问文件
webSettings.setAllowFileAccess(true);
//设置支持缩放
webSettings.setBuiltInZoomControls(true);

//传java对象到js中
webview.addJavascriptInterface(new OpenMediaPlayer(), "AndroidMediaPlayer");
webview.loadUrl("http://192.168.40.65:8080/platformWebview.html");
webview.setWebViewClient(new webViewClient());
}

//Web视图
private class webViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}

@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}

}

class OpenMediaPlayer {
String date;
String json_date;
Handler handler = new Handler();
@JavascriptInterface  <span style="color:#ff0000;">//必须有这个注解否则无法调用改函数</span>
public void playVideoWithUrl(final String test) {
handler.post(new Runnable() {

@Override
public void run() {
Intent intent = new Intent();
intent.setClass(MainActivity.this, testActivity.class);
intent.putExtra("filepath", test);
startActivity(intent);
}
});
};
}

}


三、html

<html>
<head>
<title>bbbbbbb</title>
</head>
<body>
<form>
<input type="button" id="datetext"
onclick="window.AndroidMediaPlayer.playVideoWithUrl('http://www.baidu.com');" value="" />
</form>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: