react-native icon indicating copy to clipboard operation
react-native copied to clipboard

On starting an Activity in a custom Native Module, How to get the result back?

Open lalith26 opened this issue 11 years ago • 24 comments

Hello

I have exposed a Native Module which starts an activity using an Intent. But how to get the result from the activity. I understand that startActivityForResult() won't work because the caller is not an Activity or a Fragment.

I checked the github repo. We can't even pass the Callback to the Activity using a Bundle because it does not implement Serializable or Parcelable.

Can you please explain how to solve this problem?

Thanks Lalith

lalith26 avatar Oct 11 '15 00:10 lalith26

What about trying to call JavaScriptModule in onActivityResult()?

liaohuqiu avatar Oct 11 '15 00:10 liaohuqiu

@liaohuqiu But How to Call the JavascriptModule without using the com.facebook.react.bridge.Callback? Also, How to pass this Callback object to the started Activity?

lalith26 avatar Oct 11 '15 00:10 lalith26

You have to add code in MainActivity to do that. The approach I followed is following,

1. Have a public method in your module (say FacebookLoginModule) named handleActivityResult

public boolean handleActivityResult(final int requestCode, final int resultCode, final Intent data) {
    // Your custom handling logic
    return mCallbackManager.onActivityResult(requestCode, resultCode, data);
}

2. Have a public method in the package (say FacebookLoginPackage) containing the module named handleActivityResult

private Context mContext;
private FacebookLoginModule mModuleInstance;

FacebookLoginPackage(Context activityContext) {
    mContext = activityContext;
}

@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    mModuleInstance = new FacebookLoginModule(reactContext, mContext);

    return Arrays.<NativeModule>asList(mModuleInstance);
}

...

public boolean handleActivityResult(final int requestCode, final int resultCode, final Intent data) {
    return mModuleInstance.handleActivityResult(requestCode, resultCode, data);
}

3. Call the method in MainActivity

private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;

private GoogleLoginPackage mGoogleLoginPackage;
private FacebookLoginPackage mFacebookLoginPackage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mFacebookLoginPackage = new FacebookLoginPackage(this);

            ...

            .addPackage(new MainReactPackage())
            .addPackage(mFacebookLoginPackage)

            ....
}

...

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    mFacebookLoginPackage.handleActivityResult(requestCode, resultCode, data);
}

Might not be the cleanest approach, but it works. I would certainly like if someone can provide a cleaner approach.

satya164 avatar Oct 11 '15 09:10 satya164

@satya164 Can you please provide a reference to your repo where you have implemented this?

lalith26 avatar Oct 15 '15 08:10 lalith26

@lalith26 Sorry for late reply. I'm kinda sick right now. So not much active.

Here is the repo. Check there FacebookLoginPackage - https://github.com/scrollback/io.scrollback.neighbor

satya164 avatar Oct 16 '15 23:10 satya164

@satya164 would you mind putting together a gist that demonstrates how to implement the FB login? Its a bit difficult to try and parse your entire app to see how the pieces fit together.
You would be doing the community a great service in my opinion!

jforaker avatar Oct 23 '15 22:10 jforaker

@jforaker Ideally I should publish the module on NPM. But I need to iron out some code which are specific to my use case.

BTW if you want it sooner, it's not difficult,

You could just copy the files FacebookLoginPackage and FacebookLoginModule from https://github.com/scrollback/io.scrollback.neighbor/tree/master/android/app/src/main/java/io/scrollback/neighborhoods into your project (also change package name at the top) and register the package in your MainActivity.

Then just include the Facebook SDK as per the Android docs.

satya164 avatar Oct 24 '15 13:10 satya164

@satya164 great thank you very much! It works! Can I get your permission to write a tutorial that uses your FacebookLoginPackage and FacebookLoginModule and publish it?

jforaker avatar Oct 24 '15 18:10 jforaker

@jforaker Sure.

satya164 avatar Oct 24 '15 18:10 satya164

For anyone interested in Facebook login for android, I put together a gist of my implementation, borrowed heavily from satya164:

https://gist.github.com/jforaker/bbd1b27138f259f2d7fa

And thanks again @satya164

jforaker avatar Oct 24 '15 21:10 jforaker

This feature should be included in react native by default.

It seems that only one package can handle the result in @satya164 's approach, which may not fit for my situation. My solution might be a little more complicated.

Here's my solution:

  1. create an interface called ActivityResultHandler.
    public interface ActivityResultHandler {
       void handleActivityResult(int requestCode, int resultCode, Intent data);
    }
  1. create a result manager class: In ActivityResultManager.java:
public class ActivityResultManager extends HashMap<Integer, ActivityResultHandler> {

    public void dispatch(int requestCode, int resultCode, Intent data) {
        ActivityResultHandler handler = get(requestCode);
        if(handler != null) {
            handler.handleActivityResult(requestCode, resultCode, data);
        }
    }
}
  1. add some code to the MainActivity in MainActivity, add an attribute:
private ActivityResultManager mActivityResultManager;

in the onCreate method:

mActivityResultManager = new ActivityResultManager();

add a method:

public ActivityResultManager getActivityResultManager() {
        return mActivityResultManager;
    }

add another method:

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getActivityResultManager().dispatch(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }
  1. implements the ActivityResultHandler in your module.
 class YourModule extends BaseJavaModule implements ActivityResultHandler{
    .... 
    @Override
     public void handleActivityResult(int requestCode, int resultCode, Intent data) {
           //do the stuff
    }
 }
  1. define your request code and register your module to the manager in the constructor:
public void YourModule(Foo foo) {
    // Your custom operations..
   // Find a way to access the instance of MainActivity. Probably, pass the instance to the constructor.
   mainActivity.getActivityResultManager().put(Your_Request_Code, this);
}

That's all!
Here's an example, which has multiple modules handling its own result.

mickeyinfoshan avatar Nov 19 '15 10:11 mickeyinfoshan

There is no reason that only one package will be able to get the result with my approach. You can easily call multiple methods. Also, each handler returns a boolean to check if it was handled by that. On Nov 19, 2015 15:37, "Mickey" [email protected] wrote:

This feature should be included in react native by default.

It seems that only one package can handle the result in @satya164 https://github.com/satya164 's approach, which may not fit for my situation. My solution might be a little more complicated.

Here's my solution:

  1. create an interface called ActivityResultHandler.

    public interface ActivityResultHandler { void handleActivityResult(int requestCode, int resultCode, Intent data); }

  2. create a result manager class: In ActivityResultManager.java:

public class ActivityResultManager extends HashMap<Integer, ActivityResultHandler> {

public void dispatch(int requestCode, int resultCode, Intent data) {
    ActivityResultHandler handler = get(requestCode);
    if(handler != null) {
        handler.handleActivityResult(requestCode, resultCode, data);
    }
}

}

  1. add some code to the MainActivity in MainActivity, add an attribute:

private ActivityResultManager mActivityResultManager;

in the onCreate method:

mActivityResultManager = new ActivityResultManager();

add a method:

public ActivityResultManager getActivityResultManager() { return mActivityResultManager; }

add another method:

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { getActivityResultManager().dispatch(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); }

  1. implements the ActivityResultHandler in your module.

    class YourModule extends BaseJavaModule implements ActivityResultHandler{ .... @Override public void handleActivityResult(int requestCode, int resultCode, Intent data) { //do the stuff } }

    1. define your request code and register your module to the manager in the constructor:

public void YourModule(Foo foo) { // Your custom operations.. // Find a way to access the instance of MainActivity. Probably, pass the instance to the constructor. mainActivity.getActivityResultManager().put(Your_Request_Code, this); }

That's all!

Here's an example https://github.com/mjhlybmwq/React-native-modules, which has multiple modules handling its own result.

— Reply to this email directly or view it on GitHub https://github.com/facebook/react-native/issues/3334#issuecomment-158011214 .

satya164 avatar Nov 19 '15 16:11 satya164

I found a better way:

  1. in your MainActivity:
...
private ReactInstanceManager mReactInstanceManager;
...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    mReactInstanceManager.onActivityResult(requestCode, resultCode, data);
}
  1. in your Module:
public class MyModule extends ReactContextBaseJavaModule implements ActivityEventListener {
    static final int REQUEST_VIDEO_CAPTURE = 1;

    final ReactApplicationContext reactContext;
    Promise promise;

    public GeneralIntentModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
        this.reactContext.addActivityEventListener(this);
    }

    @Override
    public String getName() {
        return "MyModule ";
    }

    @ReactMethod
    public void captureVideo(Promise promise) {
        this.promise = promise;
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (takeVideoIntent.resolveActivity(this.reactContext.getPackageManager()) != null) {
            this.reactContext.startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE, null);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        this.promise.resolve(data.getDataString());
    }
}

tal952 avatar Dec 31 '15 22:12 tal952

@tal952 Yeah. This is a much better approach.

satya164 avatar Jan 01 '16 03:01 satya164

Hi there! This issue is being closed because it has been inactive for a while.

But don't worry, it will live on with ProductPains! Check out its new home: https://productpains.com/post/react-native/on-starting-an-activity-in-a-custom-native-module-how-to-get-the-result-back

ProductPains helps the community prioritize the most important issues thanks to its voting feature. It is easy to use - just login with GitHub.

Also, if this issue is a bug, please consider sending a PR with a fix. We're a small team and rely on the community for bug fixes of issues that don't affect fb apps.

mkonicek avatar Apr 10 '16 16:04 mkonicek

Hey @tal952 !

How are you initializing the mReactInstanceManager ? I am running into the issue setting that up correctly.

jaypatel512 avatar May 04 '16 21:05 jaypatel512

Hey @jaypatel512

public class MainActivity extends ReactActivity { private ReactInstanceManager mReactInstanceManager;

twillzy avatar May 05 '16 01:05 twillzy

For examples related to communication between android and native components. Repo Link

amalChandran avatar Apr 04 '17 09:04 amalChandran

a) In Module:

1>Implement ActivityEventListener

class CustomeModule extends ReactContextBaseJavaModule implements ActivityEventListener {

2>In Constructor

CustomeModule(ReactApplicationContext reactContext) { super(reactContext); reactContext.addActivityEventListener(this); //Do not forget this at any cost }

3>In ReactMethod

@ReactMethod public void GotoNative(String resdata, Callback callback) {
Activity currentActivity = getCurrentActivity(); Intent intent = new Intent(currentActivity, DemoActivity2.class); intent.putExtra("Names",resdata+""); currentActivity.startActivityForResult(intent,REQ_CODE);
}

4>Implemented Methods

@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
    Log.e(TAG," Activity Came Back ");
}

@Override
public void onNewIntent(Intent intent) {
    Log.e(TAG," Activity onNewIntent");
}

b)Your Costume Activity (Not MainActivity)

5>Extends ReactActivity

class DemoActivity2 extends ReactActivity {

6>In DemoActivity2(Your Activity) Button Click Action

Backbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Send Data back to React Module Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); } });

Now Check in Log--- You will get what you put in

onActivityResult

Method

Note:That DemoActivity2 was not the MainActivity

Ramaraju1992 avatar Sep 08 '17 13:09 Ramaraju1992

@tal952 HRllo, Can you help me implement your solution? I could open my intent but when I close this the application stops

JoseIgnacio92 avatar Sep 18 '17 13:09 JoseIgnacio92