Android SDK: Add a repeating AlarmManager to the autostart (displaying messages in the Notification Bar)

Add a repeating AlarmManager to the Android autostart (displaying messages in the Notification Bar)

This is a tutorial on how you can set an AlarmManager to continue doing its task even after the user has rebooted his phone. In this example the AlarmManager will repeatedly display a message in the notification bar of your Android phone after you rebooted it.

  • Create a new Android application in Eclipse called „OnBootCompletedAlarmManagerExample“. The namespace is on.boot.completed.
  • The content of the main Activity looks like this:

    OnBootCompletedExampleActivity.java

    import android.app.Activity;
    import android.app.NotificationManager;
    import android.content.Context;
    import android.os.Bundle;
    
    public class OnBootCompletedExampleActivity extends Activity {
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    }
    
    @Override
    protected void onResume() {
    super.onResume();
    
    // Clear the Notification Bar after you've clicked on the message in the Notification Bar
    NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nMgr.cancelAll();
    }
    }
    
  • Create a new class called Autostart.java which extends BroadcastReceiver:

    Autostart.java

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;
    
    public class Autostart extends BroadcastReceiver {
    
    /**
    * Listens for Android's BOOT_COMPLETED broadcast and then executes
    * the onReceive() method.
    */
    @Override
    public void onReceive(Context context, Intent arg1) {
    Log.d("Autostart", "BOOT_COMPLETED broadcast received. Executing starter service.");
    
    Intent intent = new Intent(context, StarterService.class);
    context.startService(intent);
    }
    }
    

    In the AndroidManifest.xml file we are going to add this class as a receiver. See the details for that further below. This class will listen to the broadcast call the Android OS sends after the boot sequence has finished (meaning after the phone started up).

  • Create another class called StarterService.java:

    StarterService.java

    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.os.IBinder;
    import android.util.Log;
    import android.widget.Toast;
    
    public class StarterService extends Service {
    private static final String TAG = "MyService";
    
    /**
    * The started service starts the AlarmManager.
    */
    @Override
    public void onStart(Intent intent, int startid) {
    Intent i = new Intent(this, NotificationBarAlarm.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
    
    // Repeat the notification every 15 seconds (15000)
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 15000, pi);
    
    Toast.makeText(this, "My Service started", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onStart");
    }
    
    @Override
    public IBinder onBind(Intent intent) {
    return null;
    }
    
    @Override
    public void onDestroy() {
    Toast.makeText(this, "My Service stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    }
    }
    

    When the class Autostart receives the BOOT_COMPLETED broadcast from Android OS it will start the StarterService which then starts the AlarmManager which holds the PendingIntent object „pi“ which contains the NotificationBarAlarm class. NotificationBarAlarm displays a message in the Notification Bar of the Android device.

  • Next create a class called NotificationBarAlarm.java. As mentioned above this class is sending a message to the phone’s Notification Bar. The AlarmManager we called in the above class will call NotificationBarAlarm in an interval of 15 seconds after the phone has been rebooted.

    NotificationBarAlarm.java

    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.net.Uri;
    import android.util.Log;
    
    public class NotificationBarAlarm extends BroadcastReceiver {
    
    NotificationManager notifyManager;
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    Log.d("NotificationAlarm", "onReceive");
    
    notifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    
    // This Activity will be started when the user clicks the notification
    // in the notification bar
    Intent notificationIntent = new Intent(context, OnBootCompletedExampleActivity.class);
    
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    Notification notif = new Notification(R.drawable.ic_stat_rooster_col, "A new notification just popped in!", System.currentTimeMillis());
    
    // Play sound?
    // If you want you can play a sound when the notification shows up.
    // Place the MP3 file into the /raw folder.
    notif.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.jingle);
    
    notif.setLatestEventInfo(context, "Notification Title", "Notification Text", contentIntent);
    
    notifyManager.notify(1, notif);
    }
    }
    
  • And finally we update the AndroidManifest.xml with the changes we need to do in order for the application to work how we want:

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="on.boot.completed"
        android:installLocation="internalOnly"
        android:versionCode="12"
        android:versionName="1.1.8" >
    
        <uses-sdk
            android:minSdkVersion="7"
            android:targetSdkVersion="9" />
    
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
        <application
            android:icon="@drawable/icon_w_bg"
            android:label="@string/app_name" >
            <activity
                android:name="on.boot.completed.OneFunFactADayActivity"
                android:label="@string/app_name"
                android:screenOrientation="portrait"
                android:theme="@android:style/Theme.NoTitleBar" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name="EditPreferences"
                android:screenOrientation="portrait"
                android:theme="@android:style/Theme.Black.NoTitleBar" >
            </activity>
    
            <receiver android:name=".background.NotificationBarAlarm" />
            <receiver
                android:name="on.boot.completed.AutoStart"
                android:enabled="true"
                android:exported="true" >
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                </intent-filter>
            </receiver>
    
            <service
                android:name=".background.StarterService"
                android:enabled="true"
                android:exported="true" />
        </application>
    
    </manifest>
    

    A few notes about AndroidManifest.xml:

    • It’s very important to add
      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

      before the <application> tag.

    • If the app is installed on the SD Card the autostart will not work! That’s why it’s important that we add
      android:installLocation="internalOnly"

      after package=“on.boot.completed“

    • Also add
      <action android:name="android.intent.action.QUICKBOOT_POWERON" />

      in addition to

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

      to the receiver. Some HTC devices won’t catch the BOOT_COMPLETED broadcast.

That’s all. Now build and run your app. After it has been started reboot your phone. The application’s notification service should start automatically after the device has booted up and display a message in the notification bar every 15 seconds.

Here you can download the working Android project:

Repeating AlarmManager after reboot example

About Dominik
Currently working as an Android/iOS developer for Cineman, Switzerland. Owner of http://www.ukon.ch and https://play.google.com/store/apps/details?id=com.cheatdatabase

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

You must be logged in to post a comment.