Android BroadcastReceiver on startup – keep running when Activity is in Background

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);
    }
}

Leave a Comment