碎片化学习是个不好的习惯,要系统学习,建立自己的知识体系
一,简介
1. JobScheduler
Google在Android 5.0中引入JobScheduler来执行一些需要满足特定条件但不紧急的后台任务,APP利用JobScheduler来执行这些特殊的后台任务时来减少电量的消耗。
2. JobScheduler 的出现是为了解决什么问题?
这些任务有一个很大的特点-时效性不强,例如上传统计打点,备份等等一些任务。
JobScheduler是如何做到省电的,可以参考知乎网友的解答:
二.从源码角度分析JobScheduler
1.JobSchedulerService的启动
JobSchedulerService作为系统服务,在System_Server进程起来时启动它。
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搭理我们的任务
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();
}
*/
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(
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(