기본적으로 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