gpt4 book ai didi

android - WebView - 线程

转载 作者:行者123 更新时间:2023-12-03 13:16:56 25 4
gpt4 key购买 nike

[最后编辑。仍然不确定应该如何实现给出的答案。]

我无法理解 Android 应用程序中的线程问题。该应用程序基本上是一个html网页,我需要在webview和android应用程序之间来回加载和保存。我希望网页处理所有消息(因为我有一个很好的统一 css - 为了简单起见,我只在下面使用警报)。

单击保存等按钮时的主要错误:

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.

我在启动时收到这样奇怪的警告(他们应该关心我吗)?:
I/chromium: [INFO:async_pixel_transfer_manager_android.cc(60)] Async pixel transfers not supported
E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
I/chromium: [INFO:async_pixel_transfer_manager_android.cc(60)] Async pixel transfers not supported
I/Choreographer: Skipped 396 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>

主要 Activity .java
package com.example.jon.androidhtmltemplate;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

@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, webview), "Android");
}
}

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;
}
}

索引.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>

编辑(根据 Sagar 的建议):

我是 Android 开发新手(我是 Html/Javascript 程序员),所以对你的帖子有点困惑。你给了2个建议。我不确定 Callback是你第二个建议中的一个类,所以目前我会坚持你的第一个建议。

问:我需要 implements CallbackMainActivity您的类(class) 第一个 建议?

问:根据您的第一个建议,您似乎是在说我需要重写我的 public class WebAppInterface每当有对 html 页面的回调时调用。是对的吗?

所以我猜我的新 load函数将变为:
@android.webkit.JavascriptInterface
public void load(boolean isLoadExternal){
String ret, script;

ret = loadLocalExternal(isLoadExternal);

script = "javascript:CallbackAndroidLoad(\"" + ret + "\")";

// This is the only bit of the function with a call back in it
// so I need to do the special stuff on this bit alone
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);
}
}
});
}

问:什么是 activityObj ?它从何而来?如果它必须与调用函数一起传递,我该怎么做?

问:我在代码中的评论是否正确: This is the only bit of the function with a call back in it so I need to do the special stuff on this bit alone .

最佳答案

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;
}
...
}

和 runOnUiThread 如下:
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);
}
}
});

或者,您可以实现一些回调接口(interface)并在 Activity 本身中执行如下操作:
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
}
});
}

}

WebAppInterface.java
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);
}
...
}

关于android - WebView - 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50989032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com