轻扫即可取消活动


85

一旦服务完成(成功或失败),我将使用android通知来提醒用户,并且该过程完成后,我想删除本地文件。

我的问题是在失败的情况下-我想让用户使用“重试”选项。如果他选择不重试并取消该通知,我想删除为处理目的保存的本地文件(图像...)。

有没有一种方法可以捕获通知的轻扫至撤消事件?

Answers:


144

DeleteIntent:DeleteIntent是一个PendingIntent对象,可以与通知关联,并在通知被删除时被触发,以此类推:

  • 用户特定的操作
  • 用户删除所有通知。

您可以将“待定意图”设置为广播接收器,然后执行所需的任何操作。

  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
         }

  }

8
来晚了 我只是想知道是否存在类似的通知方式,builder.setAutoCancel(true);因为当用户单击通知并取消通知时,不会触发删除意图
devanshu_kaushik 2015年


是的,它可以正常工作,但不能在Oreo及更高版本的API中使用。请为奥利奥(Oreo)帮助我
彼得

@Peter为了使其能够在Oreo和Obove中工作,您需要添加以下代码行:Notification note = builder.build(); note.flags | = Notification.FLAG_AUTO_CANCEL;
Dimas Mendes

86

完全冲洗掉的答案(感谢我先生的回答):

1)创建一个接收器来处理滑动到关闭事件:

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)使用待定意向的唯一ID(在此使用通知ID)创建待定意向,否则,将为每个解雇事件重复使用相同的附加功能:

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);

不是为我工作,总是导致错误“无法实例化接收器...。没有零参数构造函数”。:只有后,我实现了另一个类似的解决方案,但与广播接收机的注册解决 stackoverflow.com/questions/13028122/...
Alexeev瓦列里

这对我有用。但是当您单击通知时无法调用该事件。我该如何监听click事件?
艾伦·沃尔克

根据文档,如果您使用setAutoCancel(true),则单击该通知将被取消,并且还会广播删除意图[ developer.android.com/reference/android/support/v4/app/…–
大约

这是可行的,除非传递了参数intent.getExtras()始终返回null,即使设置了额外功能也是如此。为了使其正常工作,您必须像这样设置动作:resultIntent.setAction(unique_action);
lxknvlk

0

另一个想法:

如果通常创建通知,则还需要执行其中的一项,两项或三项操作。我创建了一个“ 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;
}

和我用来设置删除意图这样(在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中是perform函数:

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
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.