代码之家  ›  专栏  ›  技术社区  ›  Rewind

网络视图-线程

  •  0
  • Rewind  · 技术社区  · 6 年前

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

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

    单击“保存”等按钮时出现的主要错误:

    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.
    

    这是我的密码。

    活动\主.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>
    

    主要活动

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

    索引文件

    <!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程序员),所以有点被你的帖子搞糊涂了。你给了两个建议。我不确定 Callback 是你第二个建议中的一个,所以现在我将坚持你的第一个建议。

    问: 我需要吗? implements Callback MainActivity 为您上课 第一 建议?

    问: 你的第一个建议似乎是说我需要重写我的 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 .

    1 回复  |  直到 6 年前
        1
  •  1
  •   Sagar    6 年前

    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 interface Callback {
        void loadLocalExternal(boolean isExternal);
        //define other methods.
    }
    

    main活动.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
                }
            });
        }
    
    }
    

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