Android BroadcastReceiver on startup - keep running when Activity is in Background
android, broadcastreceiver
Solution
You need to define a receiver in manifest with action name android.intent.action.BOOT_COMPLETED.
<!-- Start the Service if applicable on boot -->
<receiver android:name="com.prac.test.ServiceStarter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Make sure also to include the completed boot permission.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Use Service for this to make anything persist. And use receivers to receive Boot Up events to restart the service again if system boots..
Code for Starting Service on boot up. Make Service do your work of checking sms or whatever you want. You need to do your work in `MyPersistingService` define it your self.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ServiceStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent("com.prac.test.MyPersistingService");
i.setClass(context, MyPersistingService.class);
context.startService(i);
}
}
Problem
I'm monitoring incoming SMSs. My app is working perfectly with a `BroadcastReceiver`. However it is working from an Activity and would like to keep the `BroadcastReceiver` running all the time (and not just when my Activity is running). How can I achieve this? I've looked through the lifecycle of the `BroadcastReceiver` but all that is mentioned in the documentation is that the lifecycle is limited to the `onReceive` method, not the lifecycle of keeping the `BroadcastReceiver` checking for incoming SMS. How can I make this persistent? Thanks