BootReceiver in android

A boot receiver class is useful when you wish to run a piece of code or start a service as soon as the device has finished booting up. This is very simple to implement requiring only a class that derives from BroadcastReceiver and some configuration in the AndroidManifest.xml file.

So if you need to listen to reboot events in Android there is a simple way:

1. Add permission to RECEIVE_BOOT_COMPLETED

.. code-block:: java

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

2. Add a receiver in the AndroidManifest.xml

.. code-block:: java

<receiver android:name=".boot">
        <action android:name="android.intent.action.BOOT_COMPLETED" />

3. Implement a receiver and do implements the necessary method.

    import java.util.Calendar;
public class boot extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
       Intent myIntent = new Intent(context, MyAlarmService.class);

PendingIntent pendingIntent = PendingIntent.getService(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 1000);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);


Popular Posts