我正在使用一项每分钟在后台调用一次的服务。它使用 HTTP 请求获取数据,然后通过通知将数据通知给用户。问题是,如果通知包含上次已提取和显示的相同数据,我不希望创建通知。
我尝试设置静态变量并存储来自最新请求的数据,以将其与最新获取的数据进行比较,并以这种方式知道它是否相同以及是否在任何地方显示通知。
这是我的一些通知代码的样子:
Intent notificationIntent = new Intent(NotificationService.this, MainMenu.class);
PendingIntent contentIntent = PendingIntent.getActivity(NotificationService.this, NOTIFICATION_REQUESTS_KEY, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);;
if (!powerManager.isScreenOn())
{
mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE, "NotificationWakeLock");
mWakeLock.acquire(10000);
WakeLock mWakeLockCPU = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NotificationCPUWakeLock");
mWakeLockCPU.acquire(10000);
}
nm.notify(NOTIFICATION_REQUESTS_KEY, notification);
最佳答案
将contentText保存在本地,每次从服务器获取数据,在通知用户之前,先确认是不是不同的contentText。如果相同则不通知。
关于java - Android 通知避免不必要的通知更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024509/