你可以給下面的代碼一試,它使用了最少的AsyncTask運行GetImageRunnable
:
private boolean getImage(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
JSONObject argObject = args.getJSONObject(0);
int photoId = argObject.getInt("photoId");
final PhotoData photoData = mPhotos.get(photoId);
(new MyTask(photoData, callbackContext)).execute();
return true;
}
private class MyTask extends AsyncTask<Void, Void, Void> {
private PhotoData mPhotoData;
private CallbackContext mCallbackContext;
public MyTask(PhotoData photoData, CallbackContext callbackContext) {
mPhotoData = photoData
mCallbackContext = callbackContext;
}
protected Void doInBackground(Void... v) {
(new GetImageRunnable(photoData, callbackContext)).run();
return null;
}
protected void onProgressUpdate(Void... v) {
}
protected void onPostExecute(Void v) {
}
}
它留下的東西雖然不理想;該回調將在後臺線程中運行。如果你需要在主線程中運行,您可以掩蓋初始CallbackContext
(這是不是最後一次),並將結果傳遞到原來的onPostExecute
:
private boolean getImage(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
JSONObject argObject = args.getJSONObject(0);
int photoId = argObject.getInt("photoId");
final PhotoData photoData = mPhotos.get(photoId);
(new MyTask(photoData, callbackContext)).execute();
return true;
}
private class MyTask extends AsyncTask<Void, Void, Void> {
private PhotoData mPhotoData;
private CallbackContext mCallbackContext;
private CallbackContext mMaskedContext;
public MyTask(PhotoData photoData, CallbackContext callbackContext) {
mPhotoData = photoData
mCallbackContext = callbackContext;
mMaskedContext = new MyCallbackContext(callbackContext);
}
protected Void doInBackground(Void... v) {
(new GetImageRunnable(photoData, mMaskedContext)).run();
return null;
}
protected void onProgressUpdate(Void... v) {
}
protected void onPostExecute(Void v) {
mCallbackContext.sendPluginResult(mMaskedContext.getPluginResult());
}
}
class MyCallbackContext extends CallbackContext {
private CallbackContext mOriginalContext;
private PluginResult mPluginResult;
public MyCallbackContext(CallbackContext originalContext) {
super(originalContext.getCallbackId(), null);
mOriginalContext = originalContext;
}
public void sendPluginResult(PluginResult pluginResult) {
mPluginResult = pluginResult;
}
public pluginResult getPluginResult() {
return mPluginResult;
}
}
注:這是不是經過測試,代碼只是爲了說明這些想法。
我會嘗試使用AsyncTask並忽略CordovaInterface的看似有問題的功能。 (其他人似乎也有這個問題)。 – vbence 2015-02-23 16:44:45
@vbence添加此作爲答案,如果可能的話提供某種示例,我會將其標記爲已接受... – 2015-02-23 17:19:14