Sunday, March 29, 2015

Background worker using AlarmManager in Android

Standard
Hello All:

In our application, sometimes we need to do some operations repeatedly at a given time. Android provides different options to achieve this. One such option is use of AlarmManager.

In this post, I will share the code to achieve the above said functionality using AlarmManager.

More info related to AlarmManager can be found here.

AlarmManager provides a simple mechanism to perform operations at a given time. However one problem with AlarmManager is that they are cleared once the device is restarted. This short coming can be easily dealt with by again registering Alarms once the device is booted.

So let us start.

First we need to create a class extending BroadcastReceiver.
Let us call it BlogDemoReceiver and copy following code in it.

package com.ashwanik.demo.receivers;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.widget.Toast;


public class BlogDemoReceiver extends BroadcastReceiver {
    public final static String BlogDemoBroadcast = "com.ashwanik.actions";
    public final static int StatusNotify = 100;
    static AlarmManager alarmManager;
    static PendingIntent autoNotifyPendingIntent;
    static Intent localIntent;

    public void CancelAutoNotify(Context context) {
        localIntent = new Intent(BlogDemoBroadcast);
        localIntent.putExtra("type", BroadcastType.DEMO);
        autoNotifyPendingIntent = PendingIntent.getBroadcast(context, StatusNotify, localIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.cancel(autoNotifyPendingIntent);
    }

    private void initializeSettings(Context context) {
        if (alarmManager == null) {
            alarmManager = (AlarmManager) (context
                    .getSystemService(Context.ALARM_SERVICE));

        }
    }

    public void enableBroadCastReceiver(Context context) {
        CancelAutoNotify(context);
        localIntent = new Intent(BlogDemoBroadcast);
        localIntent.putExtra("type", BroadcastType.DEMO);
        autoNotifyPendingIntent = PendingIntent.getBroadcast(context, StatusNotify,
                localIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                SystemClock.elapsedRealtime(),
                3 * 60 * 60 * 1000, autoNotifyPendingIntent);

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        initializeSettings(context);
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
            enableBroadCastReceiver(context);
            return;
        }
        String type = BroadcastType.NONE;
        if (action.equalsIgnoreCase(BlogDemoBroadcast)) {
            type = intent.getExtras().getString("type");
        }
        if (type.equalsIgnoreCase(BroadcastType.DEMOCHANGE)) {
            enableBroadCastReceiver(context);
        } else if (type.equalsIgnoreCase(BroadcastType.DEMO)) {
            Toast.makeText(context, "Broad cast received", Toast.LENGTH_SHORT).show();
        }
    }

    public class BroadcastType {
        public static final String NONE = "N";
        public static final String DEMO = "D";
        public static final String DEMOCHANGE = "DC";
    }
}


Now in order to schedule the alarms we need to Broadcast. Below code will enable to create or update an existing alarm.

                    Intent localIntent = new Intent(BlogDemoReceiver.BlogDemoBroadcast);
                    localIntent.putExtra("type", BlogDemoReceiver.BroadcastType.DEMOCHANGE);
                    currentActivity.sendBroadcast(localIntent);
 
Now we need to do some changes in AndroidManifest.xml
Add this in <application></application>
  
   <receiver android:name=".receivers.BlogDemoReceiver">
            <intent-filter>
                <action android:name="com.ashwanik.actions" />
               
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

Hope this helps. Let me know if you face any issues. Happy coding :)
Thanks for printing this post. Hope you liked it.
Keep visiting and sharing.
Thanks,
Ashwani.

0 comments :

Post a Comment