Is there any way to trigger an event in react-native when the device is booted up. I can set a broadcast receiver in native for RECEIVE_BOOT_COMPLETED but I wanted to know how this will trigger my event written in React Native. There is a DeviceEventEmitter listener but that listener will stop when the app closes. Please suggest a way.
Asked
Active
Viewed 1,496 times
1 Answers
1
Once, I made something similar when I wanted to start the app alongside the Android OS initialization.
So, in this scenario, you can just start the main activity (or another one that make sense in your context) and let the react-native framework do the rest.
Three things are necessary to this works:
- Create a receiver class to handle the boot up event and do something for you, in this case: start the main activity to initialize your app;
- Register the class created above in your AndroidManifest.xml and add the user-permission to allow the android app receive the boot up event (do not forget the step);
- Reboot your device / emulator and wait for your app starts.
My code:
In my case, I put the created BootUpReceiver.java class at the same directory of MainActivity.java:
- Create a class named BootUpReceiver.java and replace "your_package" with your package name like bellow:
package com.your_package;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.your_package.MainActivity;
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent it = new Intent(context, MainActivity.class);
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(it);
}
}
- On your AndroidManifest.xml, put the following, and place the
receiver
tag inside yourapplication
tag:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:enabled="true"
android:name=".BootUpReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Well, I hope this help, but if I this it's not enough, please take a time and check this link of React Native documentation which explains how to connect the an Android Service to a JS Task.
It's very easy: https://facebook.github.io/react-native/docs/headless-js-android

John Harding
- 432
- 1
- 6
- 14

Fábio Filho
- 679
- 7
- 10
-
@Anarug, did you try this? – tokland Mar 12 '20 at 19:32
-
Guys, thanks for help, maybe you have some additional details to implement this using expo and config modules ? I made a thread about it… https://stackoverflow.com/questions/76163595/expo-config-plugin-for-application-auto-starting-on-android Thanks – ScreamZ May 03 '23 at 12:37