亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通知僅從服務發送一次

通知僅從服務發送一次

搖曳的薔薇 2022-12-28 10:50:01
我正在編寫一個每隔幾秒通知一次的服務,一個通知出現一次,但預期的結果是它通知多次,它在列表中多次出現。我知道通知 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();


查看完整回答
反對 回復 2022-12-28
?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

我使用了 ismail alaoui 的回答中的建議來確保通知 ID 已保存,并且我還將對調度的調用更改為如下三個參數,以便多次調用 TimerTask。

timer.schedule(task, 0, 15000);


查看完整回答
反對 回復 2022-12-28
  • 2 回答
  • 0 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號