从JobSchedulerService开始探究学习安卓framework层

本文探讨了系统级服务JobScheduler的重要性和作用,它旨在解决应用程序在特定条件下(如设备充电、连接到未计量网络或设备空闲时)高效调度任务的问题。通过JobInfo.Builder配置任务,可以设置最低延迟或在特定截止日期内完成任务。
摘要由CSDN通过智能技术生成

碎片化学习是个不好的习惯,要系统学习,建立自己的知识体系


一,简介

1. JobScheduler

      Google在Android 5.0中引入JobScheduler来执行一些需要满足特定条件但不紧急的后台任务,APP利用JobScheduler来执行这些特殊的后台任务时来减少电量的消耗。

2. JobScheduler 的出现是为了解决什么问题?

 Google 经过测试发现,每次唤醒设备,1-2秒的时候,都会消耗2分钟的待机电量,可见每次唤醒设备的时候,不仅仅是点亮了屏幕,系统也在后台处理很多事情。JobScheduler的作用是减少了设备唤醒的次数,从而减少了那些不必要的耗电
3.使用时注意的问题

 在你的任务完成的时候你需要结束你的job。因为JobScheduler为你的job持有了一个wake lock。如果你没有调用jobFinished(JobParameters params, boolean needsReschedule) 。JobScheduler将会为你的App持有一个wake lock,CPU一直处于唤醒状态,这会严重消耗设备的电量。

4.那些情况下可以考虑使用JobScheduler搭理我们的任务

Use the android.app.job.JobInfo.Builder to configure how the scheduled task should run. You can schedule the task to run under specific conditions, such as:

  • The device is charging//充电状态
  • The device is connected to an unmetered network//wifi网络
  • The system deems the device to be idle//空闲状态
  • Completion with a minimum delay or within a specific deadline.//定期任务
这些任务有一个很大的特点-时效性不强,例如上传统计打点,备份等等一些任务。
JobScheduler是如何做到省电的,可以参考知乎网友的解答:


二.从源码角度分析JobScheduler


1.JobSchedulerService的启动
JobSchedulerService作为系统服务,在System_Server进程起来时启动它。

  JobSchedulerService启动过程


[systemServer.java]
systemServer进程在启动过程中会启动各种系统基础服务
 * The main entry point from zygote.
 */
public static void main(String[] args) {
    new SystemServer().run();
}

[systemServer.java]--- run()方法中调用了启动了各种系统服务
1.startBootstrapServices();
2.startCoreServices();
3. startOtherServices();

private void run() {
     ............................................
   Looper.prepareMainLooper();
    // Initialize native services.
    System.loadLibrary("android_servers");

    // Check whether we failed to shut down last time we tried.
    // This call may not return.
    performPendingShutdown();

    // Initialize the system context.
    createSystemContext();

    // Create the system service manager.
    mSystemServiceManager new SystemServiceManager(mSystemContext);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

    // Start services.
    try {
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
    catch (Throwable ex) {
        Slog.e(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值