繁体   English   中英

通知仅从服务发送一次

[英]Notification only sent once from service

我正在编写每隔几秒钟通知一次的服务,并且通知仅显示一次,但是预期结果是它多次通知,在列表中多次出现。

我知道通知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中没有错误。

我建议您使用通知并将其存储在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();

我使用了ismail alaoui的答案中的建议来确保已保存通知ID,并且还按如下所示将调用调度更改为三个参数,以便多次调用TimerTask。

timer.schedule(task, 0, 15000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM