gpt4 book ai didi

android - 在显示之前取消 android 预定通知

转载 作者:行者123 更新时间:2023-11-29 01:11:33 26 4
gpt4 key购买 nike

如果在第一个通知后的 15 秒内尝试发送另一个通知,我正在尝试取消我请求发送给用户的通知。

这是我的代码:

全局变量:

    public NotificationManager nm;

通知函数:

    final NotificationCompat.Builder b = new NotificationCompat.Builder(this);

b.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(message);

if (nm != null) {
Log.d(TAG, "notifyThis: cancelled");
nm.cancelAll();
} else {
Log.d(TAG, "notifyThis: not cancelled");
}

nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

new Handler().postDelayed(new Runnable() {
@Override
public void run() {

nm.notify(1, b.build());
Log.d(TAG, "notifyThis: notify");

}
}, 15000);

我注意到在发布通知之前 nm 保持为 null,因此此方法不起作用,但我需要一种方法来在创建通知之后、.notify 发布通知之前删除通知。

谢谢。

最佳答案

理想情况下,您不希望像这样依赖变量的空状态。
相反,Handler 类具有删除先前安排的任务的方法。为此,您需要保留对 Handler 和 Runnable 对象的引用。

private Handler handler = new Handler();
private boolean isPosted = false;
private Runnable notificationRunnable;

void doNotification() {
final NotificationCompat.Builder b = {...}

if(isPosted) {
handler.removeCallbacks(notificationRunnable);
isPosted = false;
}
else {
notificationRunnable = new Runnable() {
@Override
public void run() {
nm.notify(1, b.build());
Log.d(TAG, "notifyThis: notify");
}
};
handler.postDelayed(notificationRunnable, 15000);
isPosted = true;
}
}

关于android - 在显示之前取消 android 预定通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42648558/

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