How to create a simple BootReceiver in Android using BroadcastReceiver
The code below is an example of how to create a BroadcastReceiver class in Android that is notified when the system is booted. In addition to the code below, you’ll need to add the receiver to your AndroidManifest.xml file, as well as add the relevant permissions to the same file.
package <packageName>;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootHelper extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
// do your thing here
}
}
}You’ll need to make the following changes to your manifest file in order to allow the broadcasted intent to reach you.
<receiver android:name=".BootHelper"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> </intent-filter> </receiver>
The above code needs to be put inside the <application> tag.
Finally, you will need to add the permission to receive the BOOT_COMPLETED intent when it is fired. The code below needs to be put inside the <manifest> tag, but outside of the <application> tag.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Now when you launch the application on an emulator, or a real phone, it should execute the code in the onReceive method. As this runs on boot you should probably keep the amount of processing to a minimum, in order to not slow the system down.
Note that you should only use this if it is necessary for your Application to do some processing when the OS is booted. For example, this is used in QuickTodo to ensure that overdue items continue to be notified, even when the device is rebooted.