我有一个服务,基本上从0到9循环,每个循环睡眠1000。此服务还会创建显示进度的通知。我想添加一些允许我取消服务的动作。我有以下代码,但它似乎不起作用。
我从以下内容中得出以下结论:
Android Jelly Bean notifications with actions
Android notification .addAction deprecated in api 23
public class FileOperationService extends IntentService {
public FileOperationService() {
super("FileOperationService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Intent deleteIntent = new Intent(this, CancelFileOperationReceiver.class);
deleteIntent.putExtra("notification_id",1);
PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(this, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManagerCompat manager = (NotificationManagerCompat.from(this));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action action = new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_close_clear_cancel, "Cancel", pendingIntentCancel).build();
builder.setContentIntent(pendingIntent);
builder.setContentText("In Progress");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.addAction(action);
builder.setProgress(9, 0, false);
for (int i = 0; i < 10; i++) {
Log.d("Service", String.valueOf(i));
builder.setProgress(9, i, false);
if (i == 9) {
builder.setContentTitle("Done");
builder.setContentText("");
builder.setProgress(0, 0, false);
manager.notify(1, builder.build());
} else {
manager.notify(1, builder.build());
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class CancelFileOperationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent();
service.setComponent(new ComponentName(context, FileOperationService.class));
context.stopService(service);
NotificationManagerCompat manager = (NotificationManagerCompat.from(context));
manager.cancel(intent.getIntExtra("notification_id",0));
Log.d("Cancel","true");
}
}
我可以看到它取消了通知,因为每次单击“取消”时它都会关闭。但是,它似乎不会取消IntentService,因为每个循环都会弹出一个新通知。
答案 0 :(得分:0)
当onHandleIntent()结束时,如果在onHandleIntent()运行时没有向其发送更多命令,则IntentService会自动停止。因此,您不要自己手动停止IntentService。
如果调用stopSelf(),则会删除在IntentService队列中等待的所有Intent。