Android(安卓)Service startForeground不显示Notification的办法
16lz
2022-05-22
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) { } }
为了避免这方法在用户不知情的情况下被滥用,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) { } }
可以选择关闭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中,而且没有显示通知。
更多相关文章
- CCRenderTexture 从后台进入前台变黑的处理(android)
- Android四大组件之~~Service
- android 4.4 设置默认日期格式
- Android——自定义通知栏使用
- Android实现系统下拉栏的消息提示——Notification
- Android通知
- android 后台长时间执行周期性定时任务 解决方案收集
- Android监听系统通知
- Android(安卓)OnLowMemory和OnTrimMemory