通过Service提权

2019-06-14  本文已影响0人  禅座

前台进程是优先级最高的类型。


image.png

在官方指南中有介绍: 创建一个前台服务用于提高app在按下home键之后的进程优先级
startForeground(ID,Notification):使Service成为前台Service。 前台服务需要在通知栏显示一条:


image.png

API level < 18 :参数2 设置 new Notification(),图标不会显示。
API level >= 18:在需要提优先级的service A启动一个InnerService。两个服务都startForeground,且绑定同样的 ID。Stop 掉InnerService ,通知栏图标被移除.
Home之后查看adj值


image.png

代码实现

public class ForgroundService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //让服务变成前台服务
        startForeground(10, new Notification());
        //如果 18 以上的设备 启动一个Service startForeground给相同的id
        //然后结束这个Service
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            startService(new Intent(this, InnnerService.class));
        }
    }


    public static class InnnerService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
            startForeground(10, new Notification());
            stopSelf();
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
}

AndroidManefest中进行静态注册

<service android:name=".service.ForgroundService" />
<service android:name=".service.ForgroundService$InnnerService" />

MainActivity开启该service

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //通过Service 提权
        startService(new Intent(this, ForgroundService.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读