我正在 IntentService 中做一些后台工作,并尝试通过单击通知来停止它。为了停止工作,我有一个静态方法,它设置一个标志。
public static void stopService() {
if (task != null) {
task.setCancelFlag(true);
}
}
该通知有一个 PendingIntent
,它将广播发送到尝试停止服务的接收器。
Intent intent = new Intent(this, AlarmReceiver.class);
intent.setAction(AlarmReceiver.STOP_SERVICE);
PendingIntent contentIntent = PendingIntent.getBroadcast(getBaseContext(), 0,
intent, 0);
notification.contentIntent = contentIntent;
接收器在收到广播时调用 stopService()
方法。
if (intent.getAction().equals(STOP_SERVICE)) {
UpdateCheckService.stopService();
}
奇怪的是,stopService()
方法没有正确调用。如果我尝试记录它,则不会执行带有标志设置的部分。即使我在接收器上设置断点并尝试调试它,它也不起作用。
但是,如果我通过单击按钮从 Activity
调用相同的方法,一切都会按预期进行。
有人知道这种奇怪的行为从何而来吗?
最佳答案
我使用 IntentService 的 Intent 来创建 PendingIntent
在onHandleIntent中我调用通知:
@Override
protected void onHandleIntent(Intent intent) {
PendingIntent pStopSelf = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
然后我添加了停止按钮并调用我的通知(在NotificationCompat.Builder上插入此行):
.addAction(R.drawable.ic_close_white_24dp, "Stop", pStopSelf)
点击通知上的停止不会触发onHandleIntent,而是调用onStartCommand
。在这里您可以检查 Intent 是否包含我们设置的停止服务的标志。
private boolean shouldStop = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getFlags() == PendingIntent.FLAG_CANCEL_CURRENT) {
Log.d(TAG, "Stop pressed");
stopSelf();
shouldStop = true;
return Service.START_NOT_STICKY;
}
return super.onStartCommand(intent, flags, startId);
}
stopSelf()
停止任何包含工作请求的 Intent,以便在 Intent 服务中执行更多工作以重新启动服务。但它不会停止服务本身。
要停止服务继续执行,请使用之前设置的 bool 值来检查工作是否应该像 onHandleIntent()
中那样继续
@Override
protected void onHandleIntent(Intent intent) {
//Invoke notification
doStuff();
}
private void doStuff() {
// do something
// check the condition
if (shouldContinue == false) {
return;
}
}
使用 bool 值在代码之间进行检查,以检查服务是否应停止并从该方法返回。
关于android - 通过单击“通知”停止 IntentService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7519187/