Recently I have been working on a simple application that should have the ability to start itself after a period of time, after the application is closed. Hopefully, it turned out that this is quite simple to implement, and to achieve this, the AlarmManager in conjuction with a BroadcastReceiver can be used.
The basic idea is as follows: the AlarmManger registers an intent, when the alarm goes off, the intent that had been registered automatically will start the target application if it is not already running. The BroadcastReceiver will be listening for that intent, and when the intent is received, it will start the desired activity from the application.
The broadcast receiver implementation looks like this:
public class OnAlarmReceive extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d(Globals.TAG, "BroadcastReceiver, in onReceive:"); // Start the MainActivity Intent i = new Intent(context, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } }
Register the OnAlarmReceive in the AndroidManifest file:
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > // ...... <receiver android:name=".OnAlarmReceive" /> </application>
And finally, here’s how to setup the alarm:
/** * Sets up the alarm * * @param seconds * - after how many seconds from now the alarm should go off */ private void setupAlarm(int seconds) { AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Intent intent = new Intent(getBaseContext(), OnAlarmReceive.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Log.d(Globals.TAG, "Setup the alarm"); // Getting current time and add the seconds in it Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, seconds); alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent); // Finish the currently running activity MainActivity.this.finish(); }
The last line from the code – finishing the current activity – is optional of course, but in case you need to finish the activity, here’s how to do.
For a live demo of the code, download the Amazing Cracked Screen application and see how it works. There you have the possibility to set up the delay in seconds when the application should start later and show the “broken” screen.
