React-Native Android - Get the variables from inte

2019-04-08 00:01发布

I'm using intent to start my React-Native app, and I'm trying to find out how to get the variables I put on my intent in the react native code. Is this possible from within react-native or do I have to write some java code to get it?

the code I use to start the app :

   Intent intent = new Intent(this, MainActivity.class);
   Intent.putExtra("alarm",true);
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(intent);

Thanks!

2条回答
Emotional °昔
2楼-- · 2019-04-08 00:09

You can pass initial props as a bundle to the third parameter in the startReactApplication method, like so:

Bundle initialProps = new Bundle();
initialProps.putString("alarm", true);

mReactRootView.startReactApplication( mReactInstanceManager, "HelloWorld", initialProps );

See this answer for more details: https://stackoverflow.com/a/34226172/293280

查看更多
Juvenile、少年°
3楼-- · 2019-04-08 00:18

Try this to get Intent params at react-native app.

In my native App, I use this code:

Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.my.react.app.package");
launchIntent.putExtra("test", "12331");
startActivity(launchIntent);

In react-native project, my MainActivity.java

public class MainActivity extends ReactActivity {

@Override
protected String getMainComponentName() {
    return "FV";
}

public static class TestActivityDelegate extends ReactActivityDelegate {
    private static final String TEST = "test";
    private Bundle mInitialProps = null;
    private final
    @Nullable
    Activity mActivity;

    public TestActivityDelegate(Activity activity, String mainComponentName) {
        super(activity, mainComponentName);
        this.mActivity = activity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Bundle bundle = mActivity.getIntent().getExtras();
        if (bundle != null && bundle.containsKey(TEST)) {
            mInitialProps = new Bundle();
            mInitialProps.putString(TEST, bundle.getString(TEST));
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected Bundle getLaunchOptions() {
        return mInitialProps;
    }
}

@Override
protected ReactActivityDelegate createReactActivityDelegate() {
    return new TestActivityDelegate(this, getMainComponentName());
  }
}

In my first Container I get the param in this.props

export default class App extends Component {

    render() {
        console.log('App props', this.props);

        //...
    }
}

The complete example I found here: http://cmichel.io/how-to-set-initial-props-in-react-native/

查看更多
登录 后发表回答