Android Phonegap: Notify javascript when an AsyncTask is finished

后端 未结 3 828
礼貌的吻别
礼貌的吻别 2020-12-02 19:19

in my app, when user click on a button in webview, a phonegap plugin will be called to trigger an asynctask to download file from internet. Now i want to send a signal back

3条回答
  •  醉话见心
    2020-12-02 19:51

    This is how I solve problems like your.

    1) Create and associate a JavascriptInterface to your WebView. A JavascriptInterface is simply a class inside which you can declare some Java method you want to use from JS.

    public class JSInterface() {
        private final CountDownLatch latch = new CountDownLatch(1);
    
        public void waitForProceed() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        public void canProceed() {
            latch.countDown();
        }
    }
    

    2) In your AsyncTask, at the end of onPostExecute() method, you have to call the canProceed() method to notify to JSInterface that it can exit from waitForProceed() method.

    public class MyAsyncTask extends AsyncTask<.......> {
        private JSInterface jsi;
        ... // other class property
    
        public MyAsyncTask(JSInterface jsi) {
            ...
            //do what you want with other class property
    
            this.jsi = jsi;
        }
    
        @Override
        public ... doInBackground(...) {
            ...
            //do something
        }
    
        @Override
        public void onPostExecute(...) {
            ...
            //do something
    
            jsi.canProceed();
        }
    }
    

    3) In your Activity you have to associate the JSInterface object to your WebView:

    WebView mWebView;
    
    ...
    
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new JSInterface(), "JSIface");
    

    4) Finally, in JS, you can call AsyncTask (I don't know how you call it, but I guess you use somthing like a JSInterface) and after call waitForProceed() method:

    startAsyncTask(); //somehow
    JSIface.waitForProceed();
    

    I hope it solves your problem ;)

提交回复
热议问题