问题
In the code below, when onActivityResult is called immediately with RESULT_CANCELED.
As suggested in other answers, I have added setActivityResultCallback just before startActivityForResult() and PluginResult#setKeepCallback(true);. But nothing is helping out. Any suggestion?
....
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
if (action.equals(ACTION_OPEN))
{
if(PermissionHelper.hasPermission(this, READ))
{
chooseFile();
}
}
else
{
return false;
}
return true;
}
public void chooseFile() {
final CordovaPlugin plugin = (CordovaPlugin) this;
Runnable worker = new Runnable() {
public void run() {
Intent filePickerIntent = new Intent(Intent.ACTION_PICK);
filePickerIntent.setType("image/*");
plugin.cordova.setActivityResultCallback(plugin);
plugin.cordova.startActivityForResult(plugin, Intent.createChooser(filePickerIntent,"Choose file"), PICK_FILE_REQUEST);
}
};
this.cordova.getThreadPool().execute(worker);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"Enter onActivityResult");
if (requestCode == PICK_FILE_REQUEST) {
Log.d(TAG,"requestCode == PICK_FILE_REQUEST");
if (resultCode == Activity.RESULT_OK) {
Log.d(TAG,"Result Ok");
Uri uri = data.getData();
Log.d(TAG, uri.toString());
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG,"Result canceled");
callbackContext.error("OPERATION_CANCELLED");
return;
}
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "UNKNOWN_ERROR"));
}
}
回答1:
I faced the same issue in one of my cordova application. I could not find the source of error but I resolved it by creating new project and installing all plugins again. It worked.
回答2:
I encoutered a similar problem with my app and after installing cordova-plugin-background-mode. For me the problem exists on android 4.4.2 and not on android 6.0. To solve that issue, I set the parameter AndroidLaunchMode in config.xml
<preference name="AndroidLaunchMode" value="singleTop" />
回答3:
You should not use the setActivityResultCallback()
method!
If you check in cordova source, you will discover that setActivityResultCallback
is an internal method with the purpose of calling onActivityResult
with the RESULT_CANCELED
parameter when a previous activity is still unfinished.
setActivityResultCallback
should be a private method in Cordova code to avoid such bugs.
来源:https://stackoverflow.com/questions/42201805/cordova-onactivityresult-is-called-immediately-after-startactivityforresult-with