Tuesday, August 26, 2014

Pending Intents

PendingIntent class provides a mechanism for creating Intents that can be fired by another application at a later time.

A PendingIntent object helps you to perform an action on your application’s behalf, often at a later time, regardless of whether your application is running or not

Intent that will be fired in response to a future event, such as a widget View being clicked or a Notification being selected from the notification panel.

PendingIntent's getActivity() method retrieves a PendingIntent object.

PendingIntent.getActivity(<context instance>, <request code>, <intent>, <flags>)

Context - Application context
request code - Request code for the intent
intent - intent for launching the target activity
flags - flags in which activity is to be launched

// Start an Activity
Intent startActivityIntent = new Intent(this, MyOtherActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, startActivityIntent, 0);

Example

    protected void displayNotification()
    {
        //---PendingIntent to launch activity if the user selects this notification---
        Intent i = new Intent(this, NotificationView.class);
        i.putExtra("notificationID", notificationID);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);

        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

//The message shown in the status bar is provided to the constructor         
        Notification notif = new Notification(R.drawable.ic_launcher, "Reminder: Meeting starts in 5 minutes", System.currentTimeMillis());


        CharSequence from = "System Alarm";
        CharSequence message = "Meeting with customer at 3pm...";
        
//Set the details of the notification using setLatestEventInfo method on the Notification instance. The details would show up when the status bar is swiped down. Also pass a pending intent that has to be invoked when the notification is tapped
        notif.setLatestEventInfo(this, from, message, pendingIntent);

        //---100ms delay, vibrate for 250ms, pause for 100 ms and
        // then vibrate for 500ms---
        notif.vibrate = new long[] { 100, 250, 100, 500};
        nm.notify(notificationID, notif);        
    }

// Broadcast an Intent
Intent broadcastIntent = new Intent(NEW_LIFEFORM_DETECTED);
PendingIntent.getBroadcast(this, 0, broadcastIntent, 0);

Example

sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);

SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);

The two PendingIntent objects will be used to send broadcasts later when an SMS message has
been sent (“SMS_SENT”) and delivered (“SMS_DELIVERED”).


No comments:

Post a Comment