这是我的代码:
活动
Intent serviceIntent = new Intent(this, DownloadService.class);
serviceIntent.putExtra("fileTitle", myFile.name);
ContextCompat.startForegroundService(this, serviceIntent);
我的服务(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);
}
我的接收者
@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);
}
}
我想根据用户操作取消我的服务(即通知上的取消按钮)。它适用于API <26,但不适用于26+。如果可能,我正在寻求帮助以解决此问题。这是我的代码:...
JobIntentService
并非旨在取消。