gpt4 book ai didi

android - 如何从 BroadcastReceiver API 26+ 取消服务

转载 作者:行者123 更新时间:2023-11-30 04:56:11 25 4
gpt4 key购买 nike

我想根据用户操作取消我的服务(即通知上的取消按钮)它适用于 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 并不是为取消而设计的。

更多信息:https://stackoverflow.com/a/47159305/6074224

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

关于android - 如何从 BroadcastReceiver API 26+ 取消服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59108519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com