当前位置:   article > 正文

Android Service startForeground不显示Notification的办法_android startforeground notification

android startforeground notification

Android 有Service后台执行重要任务时,提升后台优先级可使用startForeground方法,将使Service处于Perceptible优先级,adj=2,这一优先级比Service/BService都要高,可以一定程度上避免进程被LMK杀掉。
startForeground方法如下:

public final void startForeground(int id, Notification notification) {
        try {
            mActivityManager.setServiceForeground(
                    new ComponentName(this, mClassName), mToken, id,
                    notification, true);
        } catch (RemoteException ex) {
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

为了避免这方法在用户不知情的情况下被滥用,Android要求在使用startForeground时必须传入一个id,一个Notification,以在通知栏中显示明显通知。
重要事务干完后退出这一状态可使用方法stopForeground,如下:

    public final void stopForeground(boolean removeNotification) {
        try {
            mActivityManager.setServiceForeground(
                    new ComponentName(this, mClassName), mToken, 0, null,
                    removeNotification);
        } catch (RemoteException ex) {
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

可以选择关闭Notification。

在需要Service处于较高优先级而又不希望显示通知时,可以使用特殊技巧。如我们需要某一 ServiceX后台运行并且不能被杀掉,同时不希望被用户察觉,可以这样:
1,启动ServiceX并startForeground(id, notification)
2,立刻启动另一个ServiceY,也startForeground(id, notification),这里的id与ServiceX中startForeground的id一致;然后关闭在ServiceY中stopForeground(true)。
3,OK!

程序运行时,返回桌面,使用命令 adb shell dumpsys meminfo
进程不在 Service或BService中,而是在Perceptible中,而且没有显示通知。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/464493
推荐阅读
相关标签
  

闽ICP备14008679号