我需要在应用程序关闭时关闭通知

时间:2021-02-16 09:41:30

标签: java android multithreading notifications runnable

我有这个 Runnable 方法,它在调用后发送一个通知,并且每分钟在 HTTP 服务器上发送一个 JSON Post。因此,我编写了方法“sendNotification”以通知用户“服务”正在运行,但是当我关闭应用程序时,发送 JSON 的方法停止并且通知在通知栏上保持活动状态。我也想关闭通知。

//Runnable methods for frequency position
private final Runnable oneMinuteRunnable = new Runnable() {
    @Override
    public void run() {
        sendNotification();
        getTimestamp();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getLocation();
                doPostRequest();
            }
        }).start();
        handler.postDelayed(this, 60 * 1000);
    }

};

这是通知方式

//Make notification when the frequency service is running
public void sendNotification() {
    Notification notification = new NotificationCompat.Builder(this, com.example.httptracker.Services.Notification.NOTIFICATION_ID)
            .setSmallIcon(R.drawable.ic_baseline_run_circle_24)
            .setContentTitle("AMP Tracker")
            .setContentText("Tracker is running")
            .build();

    compat.notify(1, notification);
}

我在网上查了一下,我只看到了带有服务类的解决方案,但我需要开发一个“停止服务”按钮来取消通知。但这不是我需要的。应用关闭或方法终止后,通知应消失。

提前致谢

1 个答案:

答案 0 :(得分:0)

尝试取消您的通知:

compat.cancel(1); // assuming compat is NotificationManager instance, 1 is your id

例如onDestroy of Activity 或任何地方,当您的应用停止 oneMinuteRunnable 循环执行