Android中提高后台服务进程优先级的方法

来源:互联网 发布:ubuntu登录密码忘记了 编辑:程序博客网 时间:2024/05/21 09:50

后台服务进程不能在状态栏显示通知,所以优先级相对比较低,在内存不足的时候比较容易被系统杀掉,提高进程的优先级可以降低被杀的概率。
大致思路是:1.启动一个空的服务;
2.先设置一个前台通知,然后再取消通知
代码如下:

public class EmptyService extends Service {    @Override    public IBinder onBind(Intent arg0) {        // TODO Auto-generated method stub        return null;    }    @Override    public void onCreate() {        // TODO Auto-generated method stub        super.onCreate();    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // TODO Auto-generated method stub        try {            if (Daemonservice.contextReference != null) {                //to improve service prioty start                ((Service) Daemonservice.contextReference.get()).startForeground(1, new Notification());                super.startForeground(1, new Notification());                ((Service) Daemonservice.contextReference.get()).stopForeground(true);                //to improve service prioty end                         }            return START_NOT_STICKY;        } catch (Exception e) {            return START_NOT_STICKY;        }    }}

注:这里的Daemonservice.contextReference 是一个弱引用,在其他类中定义的静态类变量,如下所示:

 public static WeakReference<Context> contextReference ;
0 0
原创粉丝点击