有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

服务被终止时的java销毁前台通知

我有一个前台服务,可以从网上下载一些内容

不幸的是,由于报告here我的服务在接收器接收到我的服务内的广播时被终止的错误,但它的通知不会被终止,并且我在我的logcat中看到以下日志:

I/ActivityManager(449): Killing 11073:my-package-name/u0a102 (adj 0): remove task

当前台通知的父服务被操作系统杀死时,是否仍需要销毁前台通知


共 (6) 个答案

  1. # 1 楼答案

    使用stopForeground:

    @Override
    public void onDestroy() {
     // as the bug seems to exists for android 4.4
     if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT)
     {
        stopForeground(true);
     }
      super.onDestroy();
    }
    

    public void onTaskRemoved (Intent rootIntent)
    {
     // as the bug seems to exists for android 4.4
     if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT)
     {
       stopForeground(true);
     }
    }
    
  2. # 2 楼答案

    使用onDestroy()。尽管文档中说它不能保证被调用,但我已经测试了多次,唯一没有被调用的情况是当系统终止进程时,但是到那时,您的通知将被终止,所以没关系

  3. # 3 楼答案

    如果服务仍在使用以下代码运行,则在通知内定期检查(例如Handler):

    public static boolean isMyServiceRunning(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))                           {
            if (MyService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    

    如果不只是关闭通知

    private static final int DEALY = 10000;
    private Handler handler = new Handler();
    
    ...
    handler.postDelayed(ensureSericeIsRunning, DELAY);
    ...
    
    private Runnable ensureSericeIsRunning = new Runnable() {
    
        @Override
        public void run() {
            if (!isMyServiceRunning(getActivity())){
                //shut down notification
            } else {
                handler.postDelayed(ensureSericeIsRunning, DELAY);
            }
        }
    };
    
  4. # 4 楼答案

    您可以从服务类内的onStoponDestroy删除通知。 注:不保证这会起作用,在api 14及以上版本中,即使没有前台通知,服务仍可以运行,您可以返回START_STICKY,它将恢复您的服务,即使系统将其销毁,系统也将重新启动它

     @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    
  5. # 6 楼答案

    服务结束删除前台通知

    @Override
    public void onDestroy() {
        // mycleanup first
        stopForeground(true);
        super.onDestroy();
    }