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中,而且没有显示通知。

更多相关文章

  1. CCRenderTexture 从后台进入前台变黑的处理(android)
  2. Android——自定义通知栏使用
  3. Android通知
  4. Android监听系统通知
  5. android 后台长时间执行周期性定时任务 解决方案收集
  6. Android消息通知
  7. android后台运行服务,加验证
  8. android以后台service的方式获取GPRS数据
  9. android本地后台服务示例

随机推荐

  1. android中退出当前应用程序的四种方法
  2. android播放器音量控制-使用震动示例代码
  3. Android硬件加速功能
  4. 内容提供者相关技术
  5. Android(安卓)-- Context
  6. android怎么将已经安装在内存上的应用程
  7. 【工作记录】android手势事件操作记录
  8. RecyclerView的简单使用
  9. 实用Android studio gradle的离线安装方
  10. Android Chronometer控件开发