安卓如何判断 通知已经被取消或者已经过期了
时间: 2023-08-09 16:11:23 浏览: 62
在 Android 中,可以使用 NotificationManager 的 cancel() 方法来取消通知。该方法会将指定 ID 的通知从状态栏中移除。
如果您想要检查通知是否已被取消,可以使用 NotificationManager 的 getActiveNotifications() 方法获取所有当前显示的通知,然后检查是否包含要查找的通知。
如果您想要检查通知是否已过期,可以在创建通知时使用 setWhen() 方法设置通知的时间戳,然后使用 System.currentTimeMillis() 方法获取当前时间戳,比较两个时间戳的差值是否超过您设置的过期时间。
以下是一个检查通知是否已被取消或已过期的示例代码:
```java
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
// 判断通知是否已被取消
if (notificationManager.getActiveNotifications().length > 0) {
for (StatusBarNotification notification : notificationManager.getActiveNotifications()) {
if (notification.getId() == notificationId) {
// 通知仍然存在
break;
}
}
} else {
// 没有通知显示
}
// 判断通知是否已过期
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setWhen(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(30)); // 设置通知过期时间为 30 分钟后
if (System.currentTimeMillis() - builder.build().getWhen() >= 0) {
// 通知已过期
}
```