0
我有一個基本上從0-9循環的服務,併爲每個循環睡1000次。該服務還會創建一個顯示進度的通知。我想添加一些允許我取消該服務的操作。我有以下代碼,但它似乎並沒有工作。如何從通知中取消IntentService?
我想出這個從以下以下內容:
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,因爲每個循環都會彈出一個新的通知。
我試圖實現的目標是防止服務向前發展。就像我的例子一樣。如果我在第四次迭代中取消,那麼我希望服務在那裏停止。 – ank
然後,您可以清空「else if」塊,您不想執行哪個迭代任務。當迭代停止時,服務將自動停止。 – SilverSky