Android提高后台服务进程优先级

该方法应该是Android系统前台service的一个漏洞,使用该方法启动服务后, 通过adb shell cat proc/进程号/oom_adj 查看,运行在后台的服务其进程号(7.0后台进程为12)变成了 2(6.0是2,7.0是4, 前台进程0


步骤:

1、常驻服务内启动时作为前台服务启动,并启动一个只用来辅助提高进程优先级的服务FakeService

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    startForeground(FakeService.NOTIFY_ID, new Notification());
    startService(new Intent(this, FakeService.class));
    return super.onStartCommand(intent, flags, startId);
}

2、辅助服务FakeService也启动为前台服务,但是一启动马上stop掉,onDestroy中调用stopForeground()方法,这样可以把常驻服务设置为前台服务了,而通知栏也不会有通知显示。

public static int NOTIFY_ID = 100101;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Utils.logI(TAG, "onStartCommand");
    startForeground(NOTIFY_ID, new Notification());
    stopSelf();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    stopForeground(true);
    super.onDestroy();
}

猜你喜欢

转载自blog.csdn.net/forLittleBlue/article/details/59544472