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!
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/
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