I'd like to cancel my service on the user action (i.e a cancel button on the notification) It's working on API < 26, but not on 26+. I'm looking for help to fix this if possible.
Here is my code:
Activity
Intent serviceIntent = new Intent(this, DownloadService.class);
serviceIntent.putExtra("fileTitle", myFile.name);
ContextCompat.startForegroundService(this, serviceIntent);
My Service (JobIntentService)
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
Intent closeIntent = new Intent(this, NotificationReceiver.class);
closeIntent .setAction("cancel_button")
.setFlags(Intent.FLAG_RECEIVER_FOREGROUND | Intent.FLAG_RECEIVER_REPLACE_PENDING);
PendingIntent actionIntent = PendingIntent.getBroadcast(this, 0, closeIntent, PendingIntent.FLAG_CANCEL_CURRENT);
nBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setTicker("")
.setContentTitle(FILE_TITLE)
.setContentText("Download starting")
.setProgress(100,0,false)
.addAction(android.R.drawable.ic_menu_close_clear_cancel,"Cancel", actionIntent);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
if(isPostorEqualOS(Build.VERSION_CODES.O)){
startForeground(NOTIFICATION_ID, nBuilder.build());
enqueueWork(this, intent);
}
return super.onStartCommand(intent, flags, startId);
}
My Receiver
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if("cancel_button".equals(action)){
Intent stopService = new Intent(context, DownloadService.class);
boolean stop = context.stopService(stopService);
}
}