用户手动杀死进程通知栏不消失解决方案

我们都知道当应用被干掉的时候是不会收到任何通知的也不会回调onDestory()啥啥的,当你的应用被kill了这时候你的通知已经显示在通知栏了,so你应用都不存在了还显示在上面一定是不正确的,所以google了半天没啥结果,最有无奈请教国外大牛的吧,如何请教你懂的(英文关键字How to remove all notifications when an android app (activity or service) is killed),最终找到bind服务的方式解决问题。


具体代码如下:


1、manifest注册服务:

2、Activity onCreat()中   bindService(new Intent(CheckUpdateActivity.this, KillNotificationsService.class), mConnection, Context.BIND_AUTO_CREATE);

3、Activity onDestory()   unbindService(mConnection);


  private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder binder) {
            ((KillBinder) binder).service.startService(new Intent(CheckUpdateActivity.this, KillNotificationsService.class));
        }


        public void onServiceDisconnected(ComponentName className) {
        }
 };


public class KillNotificationsService extends Service {


    public class KillBinder extends Binder {
        public final Service service;


        public KillBinder(Service service) {
            this.service = service;
        }


    }


    private final IBinder mBinder = new KillBinder(this);


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


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


    @Override
    public void onCreate() {
    }
    
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        NotificationHelper.cancelNotification();
    }
}


你可能感兴趣的:(android经验传承)