【问题标题】:I need to close a notification when the application is closed应用程序关闭时我需要关闭通知
【发布时间】:2021-05-19 03:53:14
【问题描述】:

我有这个 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);
}

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

提前致谢

【问题讨论】:

    标签: java android multithreading notifications runnable


    【解决方案1】:

    尝试通过以下方式取消您的通知:

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

    在例如onDestroy 或 Activity 或当您的应用停止 oneMinuteRunnable 循环执行时的任何位置

    【讨论】:

    • 我已经尝试在“onDestroy”方法上开发那段代码,但即使我尝试使用“Toast”,它也无济于事。
    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多