【问题标题】:Notification still appear when app is closed关闭应用程序时仍会出现通知
【发布时间】:2018-01-19 17:57:47
【问题描述】:

我正在尝试在我的应用程序关闭时关闭通知,因为当我从(最近的任务/滑动退出)关闭应用程序时,通知仍然出现,如果用户尝试单击通知,应用程序将崩溃。

 @Override
    protected void onDestroy() {
        super.onDestroy();
        notification.cancel(1);
        try {
            MApplication.sBus.unregister(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

onDestroy() 中但不起作用,因为不是每次都调用onDestroy()

【问题讨论】:

  • 你试过 notificationManager.cancelAll();而不是取消,这将取消当前应用程序上下文中的所有通知。
  • @vikaskumar 感谢您的评论,但不能像我说的那样每次都调用 onDestroy,所以我可以取消通知
  • 从哪里调用活动/片段
  • 实际上我在 MainActivity 中的所有必要代码
  • 是的,onDestroy 不一定会被调用,但我想它会满足大部分时间的要求。

标签: java android notifications android-ondestroy


【解决方案1】:

问题解决了

添加一个java类文件。这里的文件名是 KillNotificationService.java

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
public class KillNotificationService extends Service{

@Override
public void onTaskRemoved(Intent rootIntent) {
//Toast.makeText(this, “service called: “, Toast.LENGTH_LONG).show();
super.onTaskRemoved(rootIntent);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getSystemService(ns);
nMgr.cancelAll();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

在您的 MainActivity oncreate 方法中调用此服务。

startService(new Intent(this, KillNotificationService.class)); 

Manifest文件中添加服务

<service android:name=".KillNotificationService"/>

【讨论】:

  • @crgarridos 尝试使用通知 ID nMgr.cancel(your_notification_id); 取消您的通知
  • 哎呀!抱歉,我的意思是:从活动中调用
  • 在我的应用程序中使用该解决方案后,我最初投票赞成他的答案,我发现startService(new Intent(this, KillNotificationService.class)); 存在问题。应用程序关闭后KillNotificationService.class 也应该被杀死。这意味着您将在下次启动应用程序时收到java.lang.IllegalStateException
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2021-05-19
  • 2017-12-16
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
相关资源
最近更新 更多