如何使用删除意图进行明确的通知,一些动作? [英] how to use delete intent to perform some action on clear notification?

查看:74
本文介绍了如何使用删除意图进行明确的通知,一些动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重置我服务的一个变量,当用户清除我的通知:这一切

I want to reset a variable of my service when user clears my notification: that's all!

环顾四周我看到每个人都建议添加删除意图在我的通知,但意图是用来启动一个活动,服务Ø什么,而我只需要一个像这样的事情:

Looking around I see that everyone suggest to add a delete intent on my notification, but intent is used to start an activity, a service o whatever while I just need a thing like this:

void onClearPressed(){
   aVariable = 0;
}

如何获得这样的结果?

how to obtain this result?

推荐答案

的通知不是由你的应用程序管理,所有的东西一样呈现出通知,并清除它们实际上是发生在另一个进程。你不能让另一个应用程序直接执行了一块code,只是因为安全原因。

Notifications are not managed by your app and all things like showing notifications and clearing them are actually happening in another process. You can't make another app directly execute a piece of code just because of security reasons.

在你的情况下,唯一的可能性是提供一个 PendingIntent 这只是环绕一个普通意图,将代表您的应用程序启动时通知被清除。 你需要使用 PendingIntent 发送广播或启动服务,然后做你想做的广播接收机或服务是什么。究竟使用从应用程序组件,您都呈现通知要看。

The only possibility in your case is to provide a PendingIntent which just wraps around a regular Intent and will be started on behalf of your app when notification is cleared. You need to use PendingIntent for sending broadcast or starting a service and then doing what you want in the broadcast receiver or in the service. What exactly to use depends on from which application component you are showing notifications.

在的情况下广播接收器,你可以只创建一个匿名内部类的广播接收机和显示通知之前动态注册。它看起来就像是:

In case of broadcast receiver you can just create an anonymous inner class for broadcast receiver and register it dynamically before showing notification. It will look something like that:

public class NotificationHelper {
    private static final String NOTIFICATION_DELETED_ACTION = "NOTIFICATION_DELETED";

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            aVariable = 0; // Do what you want here
            unregisterReceiver(this);
        }
    };

    public void showNotification(Context ctx, String text) {
        Intent intent = new Intent(NOTIFICATION_DELETED_ACTION);
        PendingIntent pendintIntent = PendingIntent.getBroadcast(ctx, 0, intent, 0);
        registerReceiver(receiver, new IntentFilter(NOTIFICATION_DELETED_ACTION));
        Notification n = new Notification.Builder(mContext).
          setContentText(text).
          setDeleteIntent(pendintIntent).
          build();
        NotificationManager.notify(0, n);
    }
}

这篇关于如何使用删除意图进行明确的通知,一些动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆