Thursday, June 23, 2016

Android Development - Schedule a Task at Certain Time

First, you will need to edit the manifest xml file and add the following:

<manifest ... >
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <application ... >
       <receiver android:name=".AlarmReceiver" />

The permission will enable the Android system to wake up at the specified time. The receiver field declares BroadcastReceiver element to be used. Here, I will be using the name AlarmReceiver.

Next, create file with something similar to below:

public class AlarmReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");

        // Put here YOUR code.
        Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example


    public void setAlarm(Context context) {
        AlarmManager alarmManager;
        PendingIntent pi;

        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent (context, AlarmReceiver.class);
        pi = PendingIntent.getBroadcast(context, 0, intent, 0);

        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, pi);

Here, setAlarm method is specifying the scheduled time to be 5 secs after the current time. At that time, onReceive method will be invoked, so you will need to place your tasks there.

Finally, edit your activity java file to add the following code to schedule:

Context context = this.getApplicationContext();
AlarmReceiver alarm = new AlarmReceiver();

That's it!

No comments:

Post a Comment