I have a service which basically loops from 0-9 and sleeps 1000 for each loop. This service also creates a notification which shows the progress. I wanted to add some action which allows me to cancel the service. I have the following codes but it doesn't seem to work.
I've come up with this following from the following:
Android Jelly Bean notifications with actions
Android notification .addAction deprecated in api 23
public class FileOperationService extends IntentService {
public FileOperationService() {
super("FileOperationService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Intent deleteIntent = new Intent(this, CancelFileOperationReceiver.class);
deleteIntent.putExtra("notification_id",1);
PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(this, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManagerCompat manager = (NotificationManagerCompat.from(this));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
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);
NotificationCompat.Action action = new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_close_clear_cancel, "Cancel", pendingIntentCancel).build();
builder.setContentIntent(pendingIntent);
builder.setContentText("In Progress");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.addAction(action);
builder.setProgress(9, 0, false);
for (int i = 0; i < 10; i++) {
Log.d("Service", String.valueOf(i));
builder.setProgress(9, i, false);
if (i == 9) {
builder.setContentTitle("Done");
builder.setContentText("");
builder.setProgress(0, 0, false);
manager.notify(1, builder.build());
} else {
manager.notify(1, builder.build());
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class CancelFileOperationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent();
service.setComponent(new ComponentName(context, FileOperationService.class));
context.stopService(service);
NotificationManagerCompat manager = (NotificationManagerCompat.from(context));
manager.cancel(intent.getIntExtra("notification_id",0));
Log.d("Cancel","true");
}
}
I can see that it cancels the notification because it closes each time I click Cancel. However, it doesn't seem to cancel the IntentService as a new notification pops up on each loop.