Android WebView-线程
[最后编辑。仍不确定给出的答案应如何实施。] 我很难理解Android应用程序中线程的问题。该应用程序基本上是一个html网页,我需要在webview和android应用程序之间来回切换以进行加载和保存。我希望该网页能够处理所有消息(因为我有一个很好的统一css-为了简单起见,我只在下面使用alert) 单击“保存”等按钮时出现的主要错误:Android WebView-线程,android,multithreading,webview,Android,Multithreading,Webview,[最后编辑。仍不确定给出的答案应如何实施。] 我很难理解Android应用程序中线程的问题。该应用程序基本上是一个html网页,我需要在webview和android应用程序之间来回切换以进行加载和保存。我希望该网页能够处理所有消息(因为我有一个很好的统一css-为了简单起见,我只在下面使用alert) 单击“保存”等按钮时出现的主要错误: W/WebView: java.lang.Throwable: A WebView method was called on thread 'JavaBri
W/WebView: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {527e3354} called on Looper (JavaBridge, tid 109) {527ece88}, FYI main Looper is Looper (main, tid 1) {527e3354})
at android.webkit.WebView.checkThread(WebView.java:2072)
at android.webkit.WebView.evaluateJavascript(WebView.java:903)
at com.example.jon.androidhtmltemplate.WebAppInterface.save(WebAppInterface.java:116)
at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:24)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
W/System.err: java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {527e3354} called on Looper (JavaBridge, tid 109) {527ece88}, FYI main Looper is Looper (main, tid 1) {527e3354})
W/System.err: at android.webkit.WebView.checkThread(WebView.java:2082)
at android.webkit.WebView.evaluateJavascript(WebView.java:903)
W/System.err: at com.example.jon.androidhtmltemplate.WebAppInterface.save(WebAppInterface.java:116)
at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:24)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
Caused by: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {527e3354} called on Looper (JavaBridge, tid 109) {527ece88}, FYI main Looper is Looper (main, tid 1) {527e3354})
at android.webkit.WebView.checkThread(WebView.java:2072)
W/System.err: ... 7 more
I/chromium: [INFO:CONSOLE(21)] "Uncaught Error: Error calling method on NPObject.", source: file:///android_asset/www/index.html (21)
I/Choreographer: Skipped 135 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 58 frames! The application may be doing too much work on its main thread.
我在启动时收到类似这样的奇怪警告(它们是否与我有关)
这是我的密码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
webappinterface.java
package com.example.jon.androidhtmltemplate;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.webkit.WebView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
// This is my class to handle interaction between my webpage and the Android app
public class WebAppInterface {
Context mContext;
WebView webview;
/** Instantiate the interface and set the context */
WebAppInterface(Context c, WebView w) {
mContext = c;
webview = w;
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
@android.webkit.JavascriptInterface
public void load(boolean isLoadExternal){
String ret, script;
ret = loadLocalExternal(isLoadExternal);
script = "javascript:CallbackAndroidLoad(\"" + ret + "\")";
if (Build.VERSION.SDK_INT >= 19 /*Might need 21*/) {
webview.evaluateJavascript(script, null);
}else {
webview.loadUrl(script);
}
}
@android.webkit.JavascriptInterface
public String loadLocalExternal(boolean isExternal) {
int length;
String ret = "";
File path = isExternal ? mContext.getExternalFilesDir(null) : mContext.getFilesDir();
String filename = "myappsavefile.glf";
File file = new File(path, filename);
FileInputStream in;
byte[] bytes;
try {
length = (int) file.length();
bytes = new byte[length];
in = new FileInputStream(file);
in.read(bytes);
in.close();
ret = new String(bytes);
} catch (Exception e) {
ret = "";
}
return ret;
}
@android.webkit.JavascriptInterface
public void save(boolean saveLocal, boolean saveExternal, String fileContent){
boolean ret = true;
String script;
if(ret && saveLocal && !saveLocalExternal(false, fileContent + " local")) ret = false;
if(ret && saveExternal && !saveLocalExternal(true, fileContent + " external")) ret = false;
script = "javascript: CallbackAndroidSave(\"" + (ret ? "true" : "false") + "\")";
if (Build.VERSION.SDK_INT >= 19 /*Might need 21*/) {
webview.evaluateJavascript(script, null);
}else {
webview.loadUrl(script);
}
}
@android.webkit.JavascriptInterface
public boolean saveLocalExternal(boolean isExternal, String fileContent) {
boolean ret = true;
File path = isExternal ? mContext.getExternalFilesDir(null) : mContext.getFilesDir();
String filename = "chartmygolf.glf";
File file = new File(path, filename);
FileOutputStream outputStream;
try {
outputStream = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContent.getBytes());
outputStream.close();
} catch (Exception e) {
//e.printStackTrace();
ret = false;
}
return ret;
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph with very interesting content.</p>
<p id="id">This is another paragraph.</p>
<button onclick="save()">Save</button>
<button onclick="loadLocal()">Load Local</button>
<button onclick="loadExternal()">Load External</button>
</body>
<script>
var isAndroid = /Android/i.test(navigator.userAgent);
document.getElementById("id").innerHTML = "This is on Android";
function save(){
Android.save(true, true, "File Contents 1");
};
function loadLocal(){
Android.load(false);
};
function loadExternal(){
Android.load(true);
};
// ---
function CallbackAndroidLoad(fileContents){
document.getElementById("id").innerHTML = fileContents.length > 0 ? "Error: Load Fail" : ("Contents: " + fileContents);
};
function CallbackAndroidSave(isSuccess){
alert(isSuccess ? "Success" : "Failure");
};
</script>
</html>
Q:什么是activityObj
?它来自哪里?如果必须通过调用函数传递,我该怎么做
Q:我在代码中的注释是否正确:
这是函数中唯一一个包含回调的位,因此我需要单独在这一位上执行特殊操作
JavascriptInterface
方法在后台线程上调用,而不是在UI线程上调用。在处理UI时,需要使用主UI线程
由于您是在单独的类中执行它,因此需要传递Activity
对象,然后在所有JavascriptInterface
方法中:
将WebAppInterface
类更改如下:
public class WebAppInterface {
Activity activityObj;
WebView webview;
/** Instantiate the interface and set the context */
WebAppInterface(Activity activityObj, WebView w) {
mContext = c;
this.activityObj = activityObj;
}
...
}
activityObj.runOnUiThread(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT >= 19 /*Might need 21*/) {
webview.evaluateJavascript(script, null);
}else {
webview.loadUrl(script);
}
}
});
全文如下:
public class WebAppInterface {
Activity activityObj;
WebView webview;
/** Instantiate the interface and set the context */
WebAppInterface(Activity activityObj, WebView w) {
mContext = c;
this.activityObj = activityObj;
}
...
}
activityObj.runOnUiThread(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT >= 19 /*Might need 21*/) {
webview.evaluateJavascript(script, null);
}else {
webview.loadUrl(script);
}
}
});
或者,您可以实现一些回调接口,并在活动本身中执行如下操作:
public interface Callback {
void loadLocalExternal(boolean isExternal);
//define other methods.
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements Callback{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView)findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("file:///android_asset/www/index.html");
webview.addJavascriptInterface(new WebAppInterface(this, this), "Android");
}
@Override
public void loadLocalExternal(boolean isExternal){
runOnUiThread(new Runnable() {
@Override
public void run() {
//Do your action here
}
});
}
}
public class WebAppInterface {
Context mContext;
private final Callback callback;
/** Instantiate the interface and set the context */
WebAppInterface(Context c, Callback callback) {
mContext = c;
this.callback = callback;
}
@android.webkit.JavascriptInterface
public String loadLocalExternal(boolean isExternal) {
callback.loadLocalExternal(isExternal);
}
...
}
WebAppInterface.java
public class MainActivity extends AppCompatActivity implements Callback{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView)findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("file:///android_asset/www/index.html");
webview.addJavascriptInterface(new WebAppInterface(this, this), "Android");
}
@Override
public void loadLocalExternal(boolean isExternal){
runOnUiThread(new Runnable() {
@Override
public void run() {
//Do your action here
}
});
}
}
public class WebAppInterface {
Context mContext;
private final Callback callback;
/** Instantiate the interface and set the context */
WebAppInterface(Context c, Callback callback) {
mContext = c;
this.callback = callback;
}
@android.webkit.JavascriptInterface
public String loadLocalExternal(boolean isExternal) {
callback.loadLocalExternal(isExternal);
}
...
}
JavascriptInterface
方法在后台线程上调用,而不是在UI线程上调用。在处理UI时,需要使用主UI线程
由于您是在单独的类中执行它,因此需要传递Activity
对象,然后在所有JavascriptInterface
方法中:
将WebAppInterface
类更改如下:
public class WebAppInterface {
Activity activityObj;
WebView webview;
/** Instantiate the interface and set the context */
WebAppInterface(Activity activityObj, WebView w) {
mContext = c;
this.activityObj = activityObj;
}
...
}
activityObj.runOnUiThread(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT >= 19 /*Might need 21*/) {
webview.evaluateJavascript(script, null);
}else {
webview.loadUrl(script);
}
}
});
全文如下:
public class WebAppInterface {
Activity activityObj;
WebView webview;
/** Instantiate the interface and set the context */
WebAppInterface(Activity activityObj, WebView w) {
mContext = c;
this.activityObj = activityObj;
}
...
}
activityObj.runOnUiThread(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT >= 19 /*Might need 21*/) {
webview.evaluateJavascript(script, null);
}else {
webview.loadUrl(script);
}
}
});
或者,您可以实现一些回调接口,并在活动本身中执行如下操作:
public interface Callback {
void loadLocalExternal(boolean isExternal);
//define other methods.
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements Callback{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView)findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("file:///android_asset/www/index.html");
webview.addJavascriptInterface(new WebAppInterface(this, this), "Android");
}
@Override
public void loadLocalExternal(boolean isExternal){
runOnUiThread(new Runnable() {
@Override
public void run() {
//Do your action here
}
});
}
}
public class WebAppInterface {
Context mContext;
private final Callback callback;
/** Instantiate the interface and set the context */
WebAppInterface(Context c, Callback callback) {
mContext = c;
this.callback = callback;
}
@android.webkit.JavascriptInterface
public String loadLocalExternal(boolean isExternal) {
callback.loadLocalExternal(isExternal);
}
...
}
WebAppInterface.java
public class MainActivity extends AppCompatActivity implements Callback{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView)findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("file:///android_asset/www/index.html");
webview.addJavascriptInterface(new WebAppInterface(this, this), "Android");
}
@Override
public void loadLocalExternal(boolean isExternal){
runOnUiThread(new Runnable() {
@Override
public void run() {
//Do your action here
}
});
}
}
public class WebAppInterface {
Context mContext;
private final Callback callback;
/** Instantiate the interface and set the context */
WebAppInterface(Context c, Callback callback) {
mContext = c;
this.callback = callback;
}
@android.webkit.JavascriptInterface
public String loadLocalExternal(boolean isExternal) {
callback.loadLocalExternal(isExternal);
}
...
}
谢谢你的回复,但我有点困惑。这就是为什么我花了一点时间来回应。我理解你在UI线程上做这些事情的意思。这是有道理的,但我仍然有点不确定如何实施它。由于我的问题中有很多代码需要您的回答,我已经更新了我的原始问题,其中引用了您的答案。这是在底部开始:编辑(由萨加尔建议):感谢萨加尔添加到您的答案,它帮助了我很多。从您在答案中添加的内容来看,WebAppInterface的函数构造函数似乎正在从上下文转换为活动。我想我需要上下文来做我以后想做的其他事情,所以我保留了mContext作为上下文,并进行了动态转换
((Activity)mContext).runOnUiThread(newrunnable()
。这似乎很有效。因此,你的回答大大增加了我对Android编程的了解。@倒带没有问题。实际上,你不需要将对象作为上下文,你只需将contextObj替换为ActivityObj,因为在层次结构中,Activity
扩展了Context
。但其他方法是不可能的。如果e只需传递应用程序上下文,而不是活动。此,然后是((活动)mContext)
将导致崩溃。感谢您的回复,但我有点困惑。这就是我花了一点时间来回复的原因。我理解您关于在UI线程上执行这些操作的说法。这是有道理的,但我仍然有点不确定如何实现它。因为我对您的回复提出的问题中有很多代码,我已经更新了我的o参考你答案的原始问题。它在底部开始:编辑(如Sagar所建议):感谢Sagar为您的答案添加内容,这对我帮助很大。从您在答案中添加的内容来看,WebAppInterface的函数构造函数似乎正在从上下文转换为活动。我想我需要上下文来完成我以后想做的其他事情,所以我保留了McContext作为上下文,并进行了动态转换((活动)mContext.runOnUiThread(新的Runnable()
。这似乎很有效。因此,你的回答大大增加了我对Android编程的了解。@倒带没有问题。实际上,你不需要将对象作为上下文,你只需将contextObj替换为ActivityObj,因为在层次结构中,Activity
扩展了Context
。但其他方法是不可能的。如果e只需传递应用程序上下文,而不是活动。这,然后((活动)mContext)
将导致崩溃。