Recently I had to work with Android JB style notifications. Unlike previous versions, we can add custom actions to these new notifications. What I had to do was upload some files to a server using a foreground service and add an option to cancel the uploading. So I added the Cancel Upload action to my notification.
To add this action I used addAction (int icon, CharSequence title, PendingIntent intent) method. When the notification is tapped I needed to open the app but I didn’t want to open the app when the Cancel action is tapped.
After some research I was managed to achieve this using a broadcast receiver.
This is my foreground service with the notification.
public class UploadService extends IntentService{ private NotificationCompat.Builder mBuilder; public UploadService() { super("UploadService"); } @Override protected void onHandleIntent(Intent intent) { Intent deleteIntent = new Intent(this, CancelUploadReceiver.class); PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(this, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT); //building the notification mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(android.R.drawable.ic_menu_upload) .setContentTitle("Uploading Media...") .setTicker("Starting uploads") .addAction(android.R.drawable.ic_menu_close_clear_cancel, "Cancel Upload", pendingIntentCancel); Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pendingIntent); mBuilder.setProgress(100, 0, true); startForeground(12345, mBuilder.build()); for(int i=0;i<10;i++){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
You need to register the CancelUploadReceiver in the manifest file.
<receiver android:name=".CancelUploadReceiver"/>
And when the “Cancel Upload” is tapped it will receive the broadcast. Then we can simply stop the service.
public class CancelUploadReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Intent service = new Intent(); service.setComponent(new ComponentName(context,UploadService.class)); context.stopService(service); } }
Great post, helped me very much!
Just one thing- you might have another notification on top of your notification so the action might not be visible (and you also can’t expand it), so you have to add “.setPriority(NotificationCompat.PRIORITY_MAX)” to your builder so your notification will be the first one
Reblogged this on hannanshaik.