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!
I think this more correct way based on answer of @Eduardo Junior
class MainDelegate(activity: ReactActivity, mainComponentName: String?) :
ReactActivityDelegate(activity, mainComponentName) {
private var params: Bundle? = null
override fun onCreate(savedInstanceState: Bundle?) {
params = plainActivity.intent.extras
super.onCreate(savedInstanceState)
}
override fun onNewIntent(intent: Intent?): Boolean {
params = intent?.extras
return super.onNewIntent(intent)
}
override fun getLaunchOptions() = params
}
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName() = "example"
override fun createReactActivityDelegate(): ReactActivityDelegate {
return MainDelegate(this, mainComponentName)
}
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With