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四大组件之~~Service
  3. android 4.4 设置默认日期格式
  4. Android——自定义通知栏使用
  5. Android实现系统下拉栏的消息提示——Notification
  6. Android通知
  7. android 后台长时间执行周期性定时任务 解决方案收集
  8. Android监听系统通知
  9. Android(安卓)OnLowMemory和OnTrimMemory

随机推荐

  1. Linux ubuntu14.04 LTS 配置 android stu
  2. android apk 升级代码
  3. 如何在Mac/Linux上设置android环境变量
  4. Android(安卓)进入后台触发的事件,一般用
  5. android app widget,安卓桌面小工具的使
  6. Java 软引用及在Android中的应用
  7. Android之混淆心得与亲身体验
  8. android从web应用读取xml和json数据实战
  9. android 三种Service
  10. android 计算字符串长度,高度