为了账号安全,请及时绑定邮箱和手机立即绑定

通知仅从服务发送一次

通知仅从服务发送一次

摇曳的蔷薇 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 关注
  • 133 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号