通知不是由您的应用管理的,所有显示通知和清除通知的内容实际上都发生在另一个进程中.由于安全原因,您不能让另一个应用程序直接执行一段代码.
在您的情况下,唯一的可能性是提供一个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);
}
}