Search code examples
androidcordovacordova-plugins

(Cordova Plugin creation) OnActivity result gets called before other activity finishes


So, I'm creating a cordova plugin that starts another activity through Action and waits for its answer. The problem is that the onActivityResult method is called before the other activity finishes.

Plugin.java

public class Plugin extends CordovaPlugin {
    CallbackContext mCallbackContext = null;

    @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
        mCallbackContext = callbackContext;
        this.cordova.setActivityResultCallback(this);
        Intent intent = new Intent();
        intent.setAction("com.myaction");
        this.cordova.startActivityForResult(this, intent, intent.getAction().hashCode());
    }

    @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Toast.makeText(this.cordova.getActivity(), "Result came " + resultCode, Toast.LENGTH_SHORT).show();
        mCallbackContext.sendPluginResult (new PluginResult (PluginResult.Status.OK));
    }
}

Basically it starts the Activity via action and while the new activity is running, the onActivityResult is called with resultCode = 0.

How can I make the onActivityResult to be called after the other activity finishes?


Solution

  • I have been struggling with this for days! In my case such scenario happened because the activity which executed the startActivityForResult method was launched as singleInstance which does not allow to start other activities in the same task as itself, thus the started activity was living in another task and unable to send results back, that's why the onActivityResult method was fired right after the startActivityForResult method. Hope it helps!