Thursday 29 January 2015

How to Create a Receiver and PendingIntent suitable for an alarm ?

Creating a Receiver for the alarm:
Now, we need a receiver to set against the alarm.

public class TestReceiver extends BroadcastReceiver
{
      public static final String tag = "TestReceiver";
      public void onReceive(Context context, Intent intent)
{
      Log.d ( tag, "Intent=" + intent );
      String message = intent.getStringExtra("message");
      Log.d ( tag, message );
}

}

You will need to register this receiver in the manifest file using the <receiver> tag.

Creating a PendingIntent suitable for an alarm:

Once we have a receiver, we can set up a PendingIntent, which is needed to set the alarm.
However, we need an intent to create a pending intent. So, we start by creating a regular intent
that can invoke the TestReceiver.

* Creating an Intent pointing to TestReceiver

Intent intent = new Intent(mContext, TestReceiver.class);
intent.putExtra("message", "Single shot alarm");

Once we have this regular intent pointing to a receiver, we need to create a pending intent that is necessary to pass to an alarm manager.

* Creating a Pending Intent

PendingIntent pi = PendingIntent.getBroadcast(
                                            mContext,  // context, or activity, or service
                                            1,              // request id, used for disambiguating this intent
                                             intent,       // intent to be delivered
                                             0);           // pending intent flags

No comments:

Post a Comment