java - 通知仅从服务发送一次

标签 java android android-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();

关于java - 通知仅从服务发送一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56402690/

相关文章:

java - Android:将 BasicNameValuePairs 的 ArrayList 传递给另一个 Activity

android - 如何创建android原生服务并使用binder与之通信?

java - 通过两个不同的 JVM 进程异常分隔 Hibernate 实例

Java 和 Scene Builder 如何禁用和启用选项卡

java - 文件在 Java 中无法正常工作

java - 如何禁用布局对齐?

jquery - 页眉、页脚固定后如何对齐内容

android - NotificationManager.cancel() 不起作用 : Notification isn't removed

android - 每个服务绑定(bind)是否需要一个 ServiceConnection?

java - 我可以在不重新启动 JVM 的情况下将新证书添加到 keystore 吗?