51 KiB
id, title, original_id
| id | title | original_id |
|---|---|---|
| version-0.33-native-modules-android | native-modules-android | native-modules-android |
Native Modules #
Sometimes an app needs access to a platform API that React Native doesn't have a corresponding module for yet. Maybe you want to reuse some existing Java code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.
We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.
The Toast Module #
This guide will use the Toast example. Let's say we would like to be able to create a toast message from JavaScript.
We start by creating a native module. A native module is a Java class that usually extends the ReactContextBaseJavaModule class and implements the functionality required by the JavaScript. Our goal here is to be able to write ToastAndroid.show('Awesome', ToastAndroid.SHORT); from JavaScript to display a short toast on the screen.
import android.widget.Toast;
import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
public class ToastModule extends ReactContextBaseJavaModule {
private static final String DURATION_SHORT_KEY = "SHORT"; private static final String DURATION_LONG_KEY = "LONG";
public ToastModule(ReactApplicationContext reactContext) { super(reactContext); } }
ReactContextBaseJavaModule requires that a method called getName is implemented. The purpose of this method is to return the string name of the NativeModule which represents this class in JavaScript. So here we will call this ToastAndroid so that we can access it through React.NativeModules.ToastAndroid in JavaScript.
An optional method called getConstants returns the constant values exposed to JavaScript. Its implementation is not required but is very useful to key pre-defined values that need to be communicated from JavaScript to Java in sync.
To expose a method to JavaScript a Java method must be annotated using @ReactMethod. The return type of bridge methods is always void. React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events (see below).
Argument Types #
The following argument types are supported for methods annotated with @ReactMethod and they directly map to their JavaScript equivalents
Read more about ReadableMap and ReadableArray
Register the Module #
The last step within Java is to register the Module; this happens in the createNativeModules of your apps package. If a module is not registered it will not be available from JavaScript.
@Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); }
@Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); }
@Override public List<NativeModule> createNativeModules( ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>();
modules<span class="token punctuation">.</span><span class="token function">add<span class="token punctuation">(</span></span><span class="token keyword">new</span> <span class="token class-name">ToastModule</span><span class="token punctuation">(</span>reactContext<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> modules<span class="token punctuation">;</span>
}
The package needs to be provided in the getPackages method of the MainApplication.java file. This file exists under the android folder in your react-native application directory. The path to this file is: android/app/src/main/java/com/your-app-name/MainApplication.java.
To make it simpler to access your new functionality from JavaScript, it is common to wrap the native module in a JavaScript module. This is not necessary but saves the consumers of your library the need to pull it off of NativeModules each time. This JavaScript file also becomes a good location for you to add any JavaScript side functionality.
- This exposes the native ToastAndroid module as a JS module. This has a
- function 'show' which takes the following parameters:
-
- String message: A string with the text to toast
-
- int duration: The duration of the toast. May be ToastAndroid.SHORT or
- ToastAndroid.LONG */ import { NativeModules } from 'react-native'; module.exports = NativeModules.ToastAndroid;
Now, from your other JavaScript file you can call the method like this:
ToastAndroid.show('Awesome', ToastAndroid.SHORT);
Beyond Toasts #
Callbacks #
Native modules also support a special kind of argument - a callback. In most cases it is used to provide the function call result to JavaScript.
...
@ReactMethod public void measureLayout( int tag, int ancestorTag, Callback errorCallback, Callback successCallback) { try { measureLayout(tag, ancestorTag, mMeasureBuffer); float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]); float relativeY = PixelUtil.toDIPFromPixel(mMeasureBuffer[1]); float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]); float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]); successCallback.invoke(relativeX, relativeY, width, height); } catch (IllegalViewOperationException e) { errorCallback.invoke(e.getMessage()); } }
...
This method would be accessed in JavaScript using:
A native module is supposed to invoke its callback only once. It can, however, store the callback and invoke it later.
It is very important to highlight that the callback is not invoked immediately after the native function completes - remember that bridge communication is asynchronous, and this too is tied to the run loop.
Promises #
Native modules can also fulfill a promise, which can simplify your code, especially when using ES2016's async/await syntax. When the last parameter of a bridged native method is a Promise, its corresponding JS method will return a JS Promise object.
Refactoring the above code to use a promise instead of callbacks looks like this:
...
@ReactMethod public void measureLayout( int tag, int ancestorTag, Promise promise) { try { measureLayout(tag, ancestorTag, mMeasureBuffer);
WritableMap map <span class="token operator">=</span> Arguments<span class="token punctuation">.</span><span class="token function">createMap<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
map<span class="token punctuation">.</span><span class="token function">putDouble<span class="token punctuation">(</span></span><span class="token string">"relativeX"</span><span class="token punctuation">,</span> PixelUtil<span class="token punctuation">.</span><span class="token function">toDIPFromPixel<span class="token punctuation">(</span></span>mMeasureBuffer<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
map<span class="token punctuation">.</span><span class="token function">putDouble<span class="token punctuation">(</span></span><span class="token string">"relativeY"</span><span class="token punctuation">,</span> PixelUtil<span class="token punctuation">.</span><span class="token function">toDIPFromPixel<span class="token punctuation">(</span></span>mMeasureBuffer<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
map<span class="token punctuation">.</span><span class="token function">putDouble<span class="token punctuation">(</span></span><span class="token string">"width"</span><span class="token punctuation">,</span> PixelUtil<span class="token punctuation">.</span><span class="token function">toDIPFromPixel<span class="token punctuation">(</span></span>mMeasureBuffer<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
map<span class="token punctuation">.</span><span class="token function">putDouble<span class="token punctuation">(</span></span><span class="token string">"height"</span><span class="token punctuation">,</span> PixelUtil<span class="token punctuation">.</span><span class="token function">toDIPFromPixel<span class="token punctuation">(</span></span>mMeasureBuffer<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
promise<span class="token punctuation">.</span><span class="token function">resolve<span class="token punctuation">(</span></span>map<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IllegalViewOperationException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
promise<span class="token punctuation">.</span><span class="token function">reject<span class="token punctuation">(</span></span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
}
...
The JavaScript counterpart of this method returns a Promise. This means you can use the await keyword within an async function to call it and wait for its result:
console<span class="token punctuation">.</span><span class="token function">log<span class="token punctuation">(</span></span>relativeX <span class="token operator">+</span> <span class="token string">':'</span> <span class="token operator">+</span> relativeY <span class="token operator">+</span> <span class="token string">':'</span> <span class="token operator">+</span> width <span class="token operator">+</span> <span class="token string">':'</span> <span class="token operator">+</span> height<span class="token punctuation">)</span><span class="token punctuation">;</span>
} catch (e) { console.error(e); } }
measureLayout();
Threading #
Native modules should not have any assumptions about what thread they are being called on, as the current assignment is subject to change in the future. If a blocking call is required, the heavy work should be dispatched to an internally managed worker thread, and any callbacks distributed from there.
Sending Events to JavaScript #
Native modules can signal events to JavaScript without being invoked directly. The easiest way to do this is to use the RCTDeviceEventEmitter which can be obtained from the ReactContext as in the code snippet below.
JavaScript modules can then register to receive events by addListenerOn using the Subscribable mixin
var ScrollResponderMixin = { mixins: [Subscribable.Mixin],
componentWillMount: function() { ... this.addListenerOn(DeviceEventEmitter, 'keyboardWillShow', this.scrollResponderKeyboardWillShow); ... }, scrollResponderKeyboardWillShow:function(e: Event) { this.keyboardWillOpenTo = e; this.props.onKeyboardWillShow && this.props.onKeyboardWillShow(e); },
You can also directly use the DeviceEventEmitter module to listen for events.
Getting activity result from startActivityForResult #
You'll need to listen to onActivityResult if you want to get results from an activity you started with startActivityForResult. To do this, the module must implement ActivityEventListener. Then, you need to register a listener in the module's constructor,
Now you can listen to onActivityResult by implementing the following method:
We will implement a simple image picker to demonstrate this. The image picker will expose the method pickImage to JavaScript, which will return the path of the image when called.
private static final int IMAGE_PICKER_REQUEST = 467081; private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST"; private static final String E_PICKER_CANCELLED = "E_PICKER_CANCELLED"; private static final String E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER"; private static final String E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND";
private Promise mPickerPromise;
public ImagePickerModule(ReactApplicationContext reactContext) { super(reactContext);
// Add the listener for onActivityResult
reactContext.addActivityEventListener(this);
}
@Override public String getName() { return "ImagePickerModule"; }
@ReactMethod public void pickImage(final Promise promise) { Activity currentActivity = getCurrentActivity();
<span class="token keyword">if</span> <span class="token punctuation">(</span>currentActivity <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
promise<span class="token punctuation">.</span><span class="token function">reject<span class="token punctuation">(</span></span>E_ACTIVITY_DOES_NOT_EXIST<span class="token punctuation">,</span> <span class="token string">"Activity doesn't exist"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">return</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
// Store the promise to resolve/reject when picker returns data mPickerPromise = promise;
<span class="token keyword">try</span> <span class="token punctuation">{</span>
final Intent galleryIntent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Intent</span><span class="token punctuation">(</span>Intent<span class="token punctuation">.</span>ACTION_PICK<span class="token punctuation">)</span><span class="token punctuation">;</span>
galleryIntent<span class="token punctuation">.</span><span class="token function">setType<span class="token punctuation">(</span></span><span class="token string">"image/*"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
final Intent chooserIntent <span class="token operator">=</span> Intent<span class="token punctuation">.</span><span class="token function">createChooser<span class="token punctuation">(</span></span>galleryIntent<span class="token punctuation">,</span> <span class="token string">"Pick an image"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
currentActivity<span class="token punctuation">.</span><span class="token function">startActivityForResult<span class="token punctuation">(</span></span>chooserIntent<span class="token punctuation">,</span> IMAGE_PICKER_REQUEST<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
mPickerPromise<span class="token punctuation">.</span><span class="token function">reject<span class="token punctuation">(</span></span>E_FAILED_TO_SHOW_PICKER<span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
mPickerPromise <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
}
// You can get the result here @Override public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (requestCode == IMAGE_PICKER_REQUEST) { if (mPickerPromise != null) { if (resultCode == Activity.RESULT_CANCELED) { mPickerPromise.reject(E_PICKER_CANCELLED, "Image picker was cancelled"); } else if (resultCode == Activity.RESULT_OK) { Uri uri = intent.getData();
<span class="token keyword">if</span> <span class="token punctuation">(</span>uri <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
mPickerPromise<span class="token punctuation">.</span><span class="token function">reject<span class="token punctuation">(</span></span>E_NO_IMAGE_DATA_FOUND<span class="token punctuation">,</span> <span class="token string">"No image data found"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
mPickerPromise<span class="token punctuation">.</span><span class="token function">resolve<span class="token punctuation">(</span></span>uri<span class="token punctuation">.</span><span class="token function">toString<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
mPickerPromise <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
} }
Listening to LifeCycle events #
Listening to the activity's LifeCycle events such as onResume, onPause etc. is very similar to how we implemented ActivityEventListener. The module must implement LifecycleEventListener. Then, you need to register a listener in the module's constructor,
Now you can listen to the activity's LifeCycle events by implementing the following methods:
onResume
}
@Override
public void onHostPause() {
// Activity onPause
}
@Override
public void onHostDestroy() {
// Activity onDestroy
}
You can edit the content above on GitHub and send us a pull request!
Recently, we have been working hard to make the documentation better based on your feedback. Your responses to this yes/no style survey will help us gauge whether we moved in the right direction with the improvements. Thank you!