我正在編寫一個每隔幾秒通知一次的服務,一個通知出現一次,但預期的結果是它通知多次,它在列表中多次出現。我知道通知 id 必須在多個通知之間更改才能出現多次,因此每次發送通知時我都使用 AtomicInteger 來增加通知 id。在類的頂部,我聲明了以下變量:AtomicInteger count;private Timer timer;然后在 onCreate() 方法中,我有以下代碼: @Override public void onCreate() { count = new AtomicInteger(0); final NotificationManager notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE); timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { Notification notification = new Notification.Builder(SiteCheckService.this) .setContentTitle("Notification") .setContentText("You should see this notification.") .setSmallIcon(R.drawable.ic_launcher_foreground) .build(); notificationManager.notify(count.incrementAndGet(), notification); } }; timer.schedule(task, 15000); }而onDestroy方法如下: @Override public void onDestroy() { timer.cancel(); timer.purge(); }我希望通知發送多次,但只發送一次。logcat 中沒有錯誤。
2 回答

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
我建議你在一個sharedPreferences元素中使用和存儲你的通知
final String Pref_Name = "Notification";
notificationPreferences = context.getSharedPreferences(Pref_Name, Context.MODE_PRIVATE);
editor = notificationPreferences.edit();
notificationCount = notificationPreferences.getInt("notifCountNumber", 0);
在你的notify()方法之后
editor.putInt("notifCountNumber",notificationCount+1);
editor.commit();

拉風的咖菲貓
TA貢獻1995條經驗 獲得超2個贊
我使用了 ismail alaoui 的回答中的建議來確保通知 ID 已保存,并且我還將對調度的調用更改為如下三個參數,以便多次調用 TimerTask。
timer.schedule(task, 0, 15000);
添加回答
舉報
0/150
提交
取消