This whole problem started when I was working with an app in React Native. I wanted the app to be able to open when it received data from another app through the “share with” intent. For example, if I share an URL through the YouTube app, I wanted my app to be recognized as one of the apps that could handle the URL and open it.
I am going to spoil the fun and tell you that there’s no easy way to do it straight through javascript with React Native. In order to make it work, you are going to have to modify some of the Android code. It’s not too hard though.
MainActivity.java
The first thing that you are going to have to do is add the following method to your MainActivity.java file (not your MainApplication.java). This is located in your java source folder once you eject your react application.
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Nullable
@Override
protected Bundle getLaunchOptions() {
Intent intent = MainActivity.this.getIntent();
Bundle bundle = new Bundle();
bundle.putString("url", intent.getStringExtra(Intent.EXTRA_TEXT));
return bundle;
}
};
}
What I am doing is getting the MainActivity’s intent and creating a new bundle. Within that bundle, I am putting in the incoming string with the key of “url” that I can use to access it later in React Native. What’s really cool is that this sets up an initial prop that can be accessed within React.
Android Manifest
Now add the following inside of your MainActivity tag in your Android Manifest. This allows your app to show up on the list of apps on the share with screen whenever text is going to be shared.
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
</intent-filter>
For more information, you can check out the Android Developer Guide.
Accessing in React
Finally, to get access to the URL string we can just use the following in the render function: {this.props.url}. This should print out the URL that the application was launched with.