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

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

    Autostart.java

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

    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

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

    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

    <br />
    import android.app.Notification;<br />
    import android.app.NotificationManager;<br />
    import android.app.PendingIntent;<br />
    import android.content.BroadcastReceiver;<br />
    import android.content.Context;<br />
    import android.content.Intent;<br />
    import android.net.Uri;<br />
    import android.util.Log;</p>
    <p>public class NotificationBarAlarm extends BroadcastReceiver {</p>
    <p>NotificationManager notifyManager;</p>
    <p>@Override<br />
    public void onReceive(Context context, Intent intent) {</p>
    <p>Log.d("NotificationAlarm", "onReceive");</p>
    <p>notifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);</p>
    <p>// This Activity will be started when the user clicks the notification<br />
    // in the notification bar<br />
    Intent notificationIntent = new Intent(context, OnBootCompletedExampleActivity.class);</p>
    <p>PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);<br />
    Notification notif = new Notification(R.drawable.ic_stat_rooster_col, "A new notification just popped in!", System.currentTimeMillis());</p>
    <p>// Play sound?<br />
    // If you want you can play a sound when the notification shows up.<br />
    // Place the MP3 file into the /raw folder.<br />
    notif.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.jingle);</p>
    <p>notif.setLatestEventInfo(context, "Notification Title", "Notification Text", contentIntent);</p>
    <p>notifyManager.notify(1, notif);<br />
    }<br />
    }<br />
    
  • 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

    <br />
    <?xml version="1.0" encoding="utf-8"?><br />
    <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" ></p>
    <p>    <uses-sdk
            android:minSdkVersion="7"
            android:targetSdkVersion="9" /></p>
    <p>    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><br />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" /><br />
        <uses-permission android:name="android.permission.WAKE_LOCK" /><br />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /></p>
    <p>    <application
            android:icon="@drawable/icon_w_bg"
            android:label="@string/app_name" ><br />
            <activity
                android:name="on.boot.completed.OneFunFactADayActivity"
                android:label="@string/app_name"
                android:screenOrientation="portrait"
                android:theme="@android:style/Theme.NoTitleBar" ><br />
                <intent-filter><br />
                    <action android:name="android.intent.action.MAIN" /></p>
    <p>                <category android:name="android.intent.category.LAUNCHER" /><br />
                </intent-filter><br />
            </activity><br />
            <activity
                android:name="EditPreferences"
                android:screenOrientation="portrait"
                android:theme="@android:style/Theme.Black.NoTitleBar" ><br />
            </activity></p>
    <p>        <receiver android:name=".background.NotificationBarAlarm" /><br />
            <receiver
                android:name="on.boot.completed.AutoStart"
                android:enabled="true"
                android:exported="true" ><br />
                <intent-filter><br />
                    <action android:name="android.intent.action.BOOT_COMPLETED" /><br />
                    <action android:name="android.intent.action.QUICKBOOT_POWERON" /><br />
                </intent-filter><br />
            </receiver></p>
    <p>        <service
                android:name=".background.StarterService"
                android:enabled="true"
                android:exported="true" /><br />
        </application></p>
    <p></manifest><br />
    

    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

Android SDK: Add application to the autostart

Add your Android application to the autostart

To add an Android application to the device’s autostart is actually pretty easy. But if some minor but important settings are wrong the autostart function doesn’t work. Here comes a fully functional example which opens your Android application after the device has finished its booting sequence.

  • Create a new Android application in Eclipse called „OnBootCompletedExample“. The namespace is on.boot.completed.
  • Leave the main Activity as is:

    OnBootCompletedExampleActivity.java

    <br />
    import android.app.Activity;<br />
    import android.os.Bundle;</p>
    <p>public class OnBootCompletedExampleActivity extends Activity {<br />
    	/** Called when the activity is first created. */<br />
    	@Override<br />
    	public void onCreate(Bundle savedInstanceState) {</p>
    <p>		super.onCreate(savedInstanceState);<br />
    		setContentView(R.layout.main);<br />
    	}<br />
    }<br />
    
  • Create a new class called Autostart.java which extends BroadcastReceiver:

    Autostart.java

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

    In the AndroidManifest.xml file we are going to add this class as a receiver. 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 which will extend Service:

    StarterService.java

    <br />
    import android.app.Service;<br />
    import android.content.Intent;<br />
    import android.os.IBinder;<br />
    import android.util.Log;<br />
    import android.widget.Toast;</p>
    <p>public class StarterService extends Service {<br />
    	private static final String TAG = "MyService";</p>
    <p>	@Override<br />
    	public IBinder onBind(Intent intent) {<br />
    		return null;<br />
    	}</p>
    <p>	@Override<br />
    	public void onDestroy() {<br />
    		Toast.makeText(this, "My Service stopped", Toast.LENGTH_LONG).show();<br />
    		Log.d(TAG, "onDestroy");<br />
    	}</p>
    <p>	/**<br />
    	 * The started service opens the Activity.<br />
    	 */<br />
    	@Override<br />
    	public void onStart(Intent intent, int startid) {<br />
    		Intent intents = new Intent(getBaseContext(), OnBootCompletedExampleActivity.class);<br />
    		intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<br />
    		startActivity(intents);</p>
    <p>		Toast.makeText(this, "My Service started", Toast.LENGTH_LONG).show();<br />
    		Log.d(TAG, "onStart");<br />
    	}<br />
    }<br />
    

    When the class Autostart receives the BOOT_COMPLETED broadcast from Android OS it will start the StarterService which then starts the Android Activity „OnBootCompletedExampleActivity“.

  • 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

    <br />
    <?xml version="1.0" encoding="utf-8"?><br />
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="on.boot.completed"
        android:installLocation="internalOnly"
        android:versionCode="1"
        android:versionName="1.0" ></p>
    <p>    <uses-sdk
            android:minSdkVersion="7"
            android:targetSdkVersion="7" /></p>
    <p>    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /></p>
    <p>    <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" ><br />
            <activity
                android:name="on.boot.completed.OnBootCompletedExampleActivity"
                android:label="@string/app_name"
                android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" ><br />
                <intent-filter><br />
                    <action android:name="android.intent.action.MAIN" /></p>
    <p>                <category android:name="android.intent.category.LAUNCHER" /><br />
                </intent-filter><br />
            </activity></p>
    <p>        <receiver android:name="on.boot.completed.Autostart" ><br />
                <intent-filter><br />
                    <action android:name="android.intent.action.QUICKBOOT_POWERON" /><br />
                    <action android:name="android.intent.action.BOOT_COMPLETED" /><br />
                </intent-filter><br />
            </receiver></p>
    <p>        <service
                android:name="on.boot.completed.StarterService"
                android:enabled="true"
                android:exported="true" /><br />
        </application></p>
    <p></manifest><br />
    

    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 turn off your phone and turn it back on and the app should start automatically after the device has booted up.

Here you can download the working Android project:
OnBootCompletedExample