如何从 BroadcastReceiver 取消服务 API 26+

How to cancel service from BroadcastReceiver API 26+

我想根据用户操作取消我的服务(即通知上的取消按钮) 它适用于 API < 26,但不适用于 26+。如果可能的话,我正在寻求帮助来解决这个问题。

这是我的代码:

Activity

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);
        }
    }

原来 JobIntentService 不是为取消而设计的。

更多信息:

我将我的服务更改为 IntentService,它正在运行。