Подтвердить что ты не робот

Поймать салфетки, чтобы отклонить событие

Я использую уведомление Android для предупреждения пользователя после завершения службы (успех или сбой), и я хочу удалить локальные файлы после завершения процесса.

Моя проблема в том, что в случае отказа - я хочу, чтобы пользователь "повторил". и если он не хочет повторять попытку и отклонять уведомление, я хочу удалить локальные файлы, сохраненные для целей процесса (изображения...).

Есть ли способ поймать событие "Свидание-отмена уведомления"?

4b9b3361

Ответ 1

DeleteIntent: DeleteIntent - это объект PendingIntent, который может быть связан с уведомлением и уволен, когда уведомление удаляется, ether:

  • Пользовательское действие
  • Пользователь Удалить все уведомления.

Вы можете установить Ожидающее намерение на широковещательный приемник, а затем выполнить любое действие, которое вы хотите.

  Intent intent = new Intent(this, MyBroadcastReceiver.class);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
  Builder builder = new Notification.Builder(this):
 ..... code for your notification
  builder.setDeleteIntent(pendingIntent);

MyBroadcastReceiver

public class MyBroadcastReceiver extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
             .... code to handle cancel
         }

  }

Ответ 2

Полностью погасший ответ (спасибо г-ну Мэй за ответ):

1) Создайте приемник, чтобы обрабатывать событие swipe-to-reject:

public class NotificationDismissedReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
      int notificationId = intent.getExtras().getInt("com.my.app.notificationId");
      /* Your code to handle the event here */
  }
}

2) Добавьте запись в манифест:

<receiver
    android:name="com.my.app.receiver.NotificationDismissedReceiver"
    android:exported="false" >
</receiver>

3) Создайте ожидающее намерение с использованием уникального идентификатора для ожидающего намерения (здесь используется идентификатор уведомления), так как без этого одни и те же дополнительные функции будут повторно использоваться для каждого события увольнения:

private PendingIntent createOnDismissedIntent(Context context, int notificationId) {
    Intent intent = new Intent(context, NotificationDismissedReceiver.class);
    intent.putExtra("com.my.app.notificationId", notificationId);

    PendingIntent pendingIntent =
           PendingIntent.getBroadcast(context.getApplicationContext(), 
                                      notificationId, intent, 0);
    return pendingIntent;
}

4) Создайте свое уведомление:

Notification notification = new NotificationCompat.Builder(context)
              .setContentTitle("My App")
              .setContentText("hello world")
              .setWhen(notificationTime)
              .setDeleteIntent(createOnDismissedIntent(context, notificationId))
              .build();

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notification);

Ответ 3

Другая идея:

если вы создаете уведомление, как правило, вам также нужны действия один, два или три из них. Я создал "NotifyManager", он создает все уведомления, которые мне нужны, а также получает все вызовы Intent. Поэтому я могу управлять всеми действиями, а также улавливать событие увольнения в ОДНОМ месте.

public class NotifyPerformService extends IntentService {

@Inject NotificationManager notificationManager;

public NotifyPerformService() {
    super("NotifyService");
    ...//some Dagger stuff
}

@Override
public void onHandleIntent(Intent intent) {
    notificationManager.performNotifyCall(intent);
}

чтобы создать deleteIntent, используйте это (в NotificationManager):

private PendingIntent createOnDismissedIntent(Context context) {
    Intent          intent          = new Intent(context, NotifyPerformMailService.class).setAction("ACTION_NOTIFY_DELETED");
    PendingIntent   pendingIntent   = PendingIntent.getService(context, SOME_NOTIFY_DELETED_ID, intent, 0);

    return pendingIntent;
}

и THAT, который я использую для установки намерения delete, как это (в NotificationManager):

private NotificationCompat.Builder setNotificationStandardValues(Context context, long when){
    String                          subText = "some string";
    NotificationCompat.Builder      builder = new NotificationCompat.Builder(context.getApplicationContext());


    builder
            .setLights(ContextUtils.getResourceColor(R.color.primary) , 1800, 3500) //Set the argb value that you would like the LED on the device to blink, as well as the rate
            .setAutoCancel(true)                                                    //Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel.
            .setWhen(when)                                                          //Set the time that the event occurred. Notifications in the panel are sorted by this time.
            .setVibrate(new long[]{1000, 1000})                                     //Set the vibration pattern to use.

            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
            .setSmallIcon(R.drawable.ic_white_24dp)
            .setGroup(NOTIFY_GROUP)
            .setContentInfo(subText)
            .setDeleteIntent(createOnDismissedIntent(context))
    ;

    return builder;
}

и, наконец, в том же NotificationManager есть функция выполнения:

public void performNotifyCall(Intent intent) {
    String  action  = intent.getAction();
    boolean success = false;

    if(action.equals(ACTION_DELETE)) {
        success = delete(...);
    }

    if(action.equals(ACTION_SHOW)) {
        success = showDetails(...);
    }

    if(action.equals("ACTION_NOTIFY_DELETED")) {
        success = true;
    }


    if(success == false){
        return;
    }

    //some cleaning stuff
}