Android Phonegap:当AsyncTask完成时通知javascript

Android Phonegap: Notify javascript when an AsyncTask is finished

本文关键字:完成时 通知 javascript AsyncTask Phonegap Android      更新时间:2023-09-26

在我的应用程序中,当用户点击webview中的按钮时,将调用phonegap插件来触发从互联网下载文件的asynctask。现在我想在asynctask完成时发送一个信号回javascript部分。但我不知道如何做到这一点,因为我的插件已经在asynctask完成之前发送了一些东西。有没有人知道我如何通知我的javascript部分没有插件在Phonegap?

我也在Phonegap谷歌群里问过这个问题,下面是Simon Mac Donald的回答。它非常适合我:


你可以很容易地使用Plugin API来处理这种情况。它在核心API项Connection和Battery中实现。你需要做的是:

1)在你的插件的execute()方法中保存你得到的callbackId。

2)返回NO_RESULT插件结果并设置keep回调id为true。

    PluginResult pluginResult = new  PluginResult(PluginResult.Status.NO_RESULT); 
    pluginResult.setKeepCallback(true); 
    return pluginResult; 

3)当你的异步java方法完成返回另一个插件结果,像这样:

    PluginResult result = new PluginResult(PluginResult.Status.OK, data); 
    result.setKeepCallback(false); 
    this.success(result, this.myCallbackId); 

正如我所说的,你可以看看GitHub中的代码,看看我们是如何将其用于连接和电池的。


我就是这样解决你这样的问题的。

1)创建并关联一个JavascriptInterface到你的WebView。JavascriptInterface只是一个类,你可以在里面声明一些你想在JS中使用的Java方法。

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)在你的AsyncTask中,在onPostExecute()方法的末尾,你必须调用canProceed()方法来通知JSInterface它可以退出waitForProceed()方法。

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)在你的活动中,你必须将JSInterface对象关联到你的WebView:

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

4)最后,在JS中,您可以调用AsyncTask(我不知道您如何调用它,但我猜您使用类似JSInterface的东西),然后调用waitForProceed()方法:

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

我希望这能解决你的问题。

下面是一个详细的例子:

让我们创建一些接口,当AsyncTask将完成的东西,也就是当onPostExecute调用。

在我的例子中,我们获取一些JSONArray数据

MyTaskListenerItf.java

public interface GroupTaskListenerItf {
   public void onTaskDone(JSONArray groupArray);
}

AsyncTask模板如下:

MyBuildTask.java

public class MyBuildTask extends AsyncTask<Void, Void, SomeData>{
    private MyTaskListenerItf mTl = null;
    public MyBuildTask(Context context,  MyTaskListenerItf tl) {
        super();
        this.mContext = context;        
        this.mTl = tl;
    }
       @Override
       protected SomeData doInBackground(Void... params) {
          /* ... */
        }
    @Override
    protected void onPostExecute(WmTransferItem transferItem) {
       // ...

        if(this.mTl != null){           
            JSONArray data  = new JSONArray("");            
            this.mTl.onTaskDone(data);
        }      
       // ..
     }
}

那么现在我们的CordovaPlugin类应该是这样的:

MyCordovaPlugin.java

public class MyCordovaPlugin extends CordovaPlugin implements GroupTaskListenerItf {
       // we need this callback when Task will finish
   private CallbackContext mMyCallbackContext = null; 
   @Override
   public boolean execute(String action, JSONArray args,CallbackContext callbackContext) throws JSONException {
          if("runMe".equals(action)){
             final GroupTaskListenerItf gt = this;
              mMyCallbackContext = callbackContext;
             // pass our 'GroupTaskListenerItf' interface to async class    
              MyBuildTask task = new MyBuildTask(cordova.getActivity(), gt);
              task.execute();
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult); 
          }
          else{
              this.cordova.getThreadPool().execute( new Runnable() {
                   public void run() {
                     // BTW, here you might run something else out of UI Thread
                    }
             });
          }
   }
/* ... */
 @Override
public void onTaskDone(JSONArray data) {
if (this.mGroupCallbackContext != null) {
        PluginResult result = new PluginResult(PluginResult.Status.OK, data);
        result.setKeepCallback(false);
        this.mMyCallbackContext.sendPluginResult(result);
      }     
}

希望对大家有所帮助。