gpt4 book ai didi

android - 如何使用删除 Intent 对清除通知执行某些操作?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:31:36 36 4
gpt4 key购买 nike

我想在用户清除我的通知时重置我的服务变量:仅此而已!

环顾四周,我看到每个人都建议在我的通知中添加删除 Intent ,但 Intent 用于启动 Activity ,服务或其他任何东西,而我只需要这样的东西:

void onClearPressed(){
aVariable = 0;
}

如何得到这个结果?

最佳答案

通知不是由您的应用程序管理的,所有诸如显示和清除通知之类的事情实际上都发生在另一个进程中。出于安全原因,您不能让另一个应用程序直接执行一段代码。

在您的情况下,唯一的可能性是提供一个 PendingIntent,它只是环绕一个常规 Intent,并在清除通知时代表您的应用程序启动。您需要使用 PendingIntent 发送广播或启动服务,然后在广播接收器或服务中执行您想要的操作。具体使用什么取决于您从哪个应用程序组件显示通知。

如果是广播接收器,您只需为广播接收器创建一个匿名内部类,并在显示通知之前动态注册它。它看起来像这样:

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

关于android - 如何使用删除 Intent 对清除通知执行某些操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13028122/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com