Skip to content

Instantly share code, notes, and snippets.

@Eldelshell
Created December 26, 2016 22:31
Show Gist options
  • Save Eldelshell/7acde8ec548609937a1716ad9a686117 to your computer and use it in GitHub Desktop.
Save Eldelshell/7acde8ec548609937a1716ad9a686117 to your computer and use it in GitHub Desktop.
Receive input from Android apps on your React Native (0.39) application

For a react-native app I wanted to be able to receive any URL from the browser or any other application which shares URL's with the system sharing system (or whatever it's called).

I find it weird that RN doesn't provide this out of the box but it's easy to implement.

import React from 'react';
import { Navigator, AppRegistry } from 'react-native';
import Splash from './app/views/Splash';
export default class MyApp extends React.Component {
// Navigation and route handling removed for convinience.
render(){
// We should receieve this from the Android MainActivity
const importUrl = this.props.importUrl;
return (
<Navigator
initialRoute={{ component: Splash, passProps: { importUrl: importUrl } }}
configureScene={ this.configureScene }
renderScene={(route, nav) => {return this.renderScene(route, nav)}}
/>
);
}
}
AppRegistry.registerComponent('MyApp', () => MyApp);
package com.myapp;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
// Standard Activiy generated by react-native
public class MainActivity extends ReactActivity {
// Store the URL we're receiving from the share system
public static String importUrl;
@Override
protected String getMainComponentName() {
return "MyApp";
}
/**
* Since MainActivity is our entry Intent, we have to override the default
* onCreate from ReactActivity and obtain the parameter "importUrl"
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
final Intent intent = this.getIntent();
final String action = intent.getAction();
final String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null && "text/plain".equals(type)) {
// Extract the URL from the Intent and set it to our variable
MainActivity.importUrl = intent.getStringExtra(Intent.EXTRA_TEXT);
}
super.onCreate(savedInstanceState);
}
/**
* The magic happens here. getLaunchOptions works on a delegate since version 0.34 of RN
* Check https://github.com/facebook/react-native/pull/9320 for more information.
*/
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Override
protected Bundle getLaunchOptions() {
Bundle initialProps = new Bundle();
// Set the value from our static variable for the app
initialProps.putString("importUrl", MainActivity.importUrl);
// Since importUrl is static we have to reset it
MainActivity.importUrl = null;
return initialProps;
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment