I am aware of the answer here. The solution is to use a broadcast receiver and starting a service inside of it, then registering it in the manifest. The problem is that I am coding in react-native but had to write some native code. I do have a broadcast receiver but its defined inside my ReactContextBaseJavaModule
as following:
public class PhonePositionModule extends ReactContextBaseJavaModule {
public PhonePositionModule(ReactApplicationContext reactContext) {
super(reactContext);
BroadcastReceiver phonePositionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
float[] message = intent.getFloatArrayExtra("message");;
PhonePositionModule.this.sendEvent(message);
}
};
LocalBroadcastManager.getInstance(getReactApplicationContext()).registerReceiver(phonePositionReceiver, new IntentFilter("PhonePosUpdate"));
}
What I did is create a new class that extends the broadcast receiver and started the service from there, but I do not like this approach because this means that I am starting a service with two ways (or two different codes).
1) The user starts it by calling a react method:
@ReactMethod
public void startService(Promise promise) {
String result = "Success";
try {
Intent intent = new Intent(PhonePositionService.FOREGROUND); ///////
intent.setClass(this.getReactApplicationContext(), PhonePositionService.class);
getReactApplicationContext().startService(intent);
} catch (Exception e) {
promise.reject(e);
return;
}
promise.resolve(result);
}
2) It starts after boot up by the custom made broadcast receiver:
public class BootCompletedIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, PhonePositionService.class);
context.startService(pushIntent);
}
}
}
I think this is the reason my app crashes somethings on entry. Is there a way to call startService when booting up rather than creating the additional class like above?