Android为TV端助力之Webview与JS双向交互

package com.hhzt.iptv.adservice;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView; /**
* Created by Administrator on 2019-04-16.
*/ public class AdActivity extends Activity { private WebView mWebView;
private WebSettings mWebSetting;
TextView beginLoading,endLoading,loading,mtitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ad);
mWebView = (WebView)findViewById(R.id.webView1);
beginLoading = (TextView) findViewById(R.id.text_beginLoading);
endLoading = (TextView) findViewById(R.id.text_endLoading);
loading = (TextView) findViewById(R.id.text_Loading);
mtitle = (TextView) findViewById(R.id.title);
mWebSetting = mWebView.getSettings();
mWebSetting.setJavaScriptEnabled(true); /**
* 传一个Android对象给JS,JS拿到对象以后就可以调用你传递的对象里面的方法
*/
mWebView.addJavascriptInterface(new MyWeb(),"test");//AndroidtoJS类对象映射到js的test对象
mWebView.loadUrl("file:///android_asset/index.html"); /**
* (2) WebViewClient类(主要作用是:处理各种通知 & 请求事件)
*/
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//使得打开网页时不调用系统浏览器, 而是在本WebView中显示
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
} @Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//设定加载开始的操作
// super.onPageStarted(view, url, favicon);
System.out.println("开始加载了");
beginLoading.setText("开始加载了");
} @Override
public void onPageFinished(WebView view, String url) {
//设定加载结束的操作
// super.onPageFinished(view, url);
endLoading.setText("结束加载了");
// Android版本变量
final int version = Build.VERSION.SDK_INT;
/**
* 因为该方法在 Android 4.4 版本才可使用,所以使用时需进行版本判断
* android 调用JS代码。需要在webview也没加载完成时调用,否则无效
*/
if (version < 18) {
mWebView.loadUrl("javascript:callAndroid()");
} else {
mWebView.evaluateJavascript("javascript:callAndroid()", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
//此处为 js 返回的结果
Log.i("TAG","onReceiveValue:"+value);
}
});
}
} @Override
public void onLoadResource(WebView view, String url) {
//设定加载资源的操作
super.onLoadResource(view, url);
} @Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { } @Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//该方法传回了错误码,根据错误类型可以进行不同的错误分类处理
Log.i("TAG","onReceivedError:"+errorCode);
super.onReceivedError(view, errorCode, description, failingUrl);
}
}); /**
* (3) WebChromeClient类( 作用:辅助 WebView 处理 Javascript 的对话框,网站图标,网站标题等等。)
*/
mWebView.setWebChromeClient(new WebChromeClient(){ @Override
public void onProgressChanged(WebView view, int newProgress) {
Log.i("TAG","onProgressChanged:"+newProgress);
if (newProgress < 100) {
String progress = newProgress + "%";
loading.setText(progress);
} else if (newProgress == 100) {
String progress = newProgress + "%";
loading.setText(progress);
}
}
//获取网站标题
@Override
public void onReceivedTitle(WebView view, String title) {
// super.onReceivedTitle(view, title);
System.out.println("标题在这里");
mtitle.setText(title);
}
//获取网站logo
@Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
} @Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.i("TAG","onConsoleMessage:"+consoleMessage.message()+ "-- from line "+consoleMessage.lineNumber()+" of "+consoleMessage.sourceId());
//这个方法返回Webview加载JS时的日志信息
return super.onConsoleMessage(consoleMessage);
} }); } @Override
protected void onResume() {
super.onResume(); } //销毁Webview
@Override
protected void onDestroy() {
if (mWebView != null) {
// mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
mWebView.clearHistory();
((ViewGroup) mWebView.getParent()).removeView(mWebView);
mWebView.destroy();
mWebView = null;
}
super.onDestroy();
} //点击返回上一页面而不是退出浏览器
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
} index.hdml界面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Carson</title>
</head>
<body>
//点击按钮则调用callAndroid函数
<button onclick="callAndroid()"></button>
</body>
<script>
function callAndroid(){
// 由于对象映射,所以调用test对象等于调用Android映射的对象,注意此处不能定义test,如果定义的那就是一个新的对象,将会提示无法找到hello方法
test.hello("js调用了android中的hello方法");
}
</script>
</html>
友情提示:修改index.html文件时,记得clean project一下,因为你运行时间AS编译器不会去编译assets里面的文件,或者在项目的build.gradle加上
sourceSets {
main {
manifest.srcFile 'src/main/AndroidManifest.xml'
java.srcDirs = ['src/main/java', 'src/main/aidl']
resources.srcDirs = ['src/main/java', 'src/main/aidl']
aidl.srcDirs = ['src/main/aidl']
res.srcDirs = ['src/main/res']
assets.srcDirs = ['src/main/assets']
}
}

上一篇:shell脚本 统计一段程序运行时间【转】


下一篇:解决 jQuery.UI.Resizable aspectRatio在init后无法重新设置