Android电量优化之JobScheduler
程序员文章站
2023-12-25 12:50:15
android电量优化之jobscheduler。jobscheduler目前就我认知解决4个问题:
1.打包操作
2.充足电量、充电情况
3.wifi、移动数据情况
4.休眠
service...
android电量优化之jobscheduler。jobscheduler目前就我认知解决4个问题:
1.打包操作
2.充足电量、充电情况
3.wifi、移动数据情况
4.休眠
service
package com.example.demo; import android.app.job.jobparameters; import android.app.job.jobservice; import android.content.context; import android.net.connectivitymanager; import android.net.networkinfo; import android.util.log; public class xjobservice extends jobservice { private static final string tag = "xbh"; @override public boolean onstartjob(jobparameters params) { if (isnetworkconnected()) { log.i(tag, "我进行了网络请求"); return true; } return false; } @override public boolean onstopjob(jobparameters params) { return false; } private boolean isnetworkconnected() { connectivitymanager connectivitymanager = (connectivitymanager) getsystemservice(context.connectivity_service); networkinfo networkinfo = null; if (connectivitymanager != null) { networkinfo = connectivitymanager.getactivenetworkinfo(); } return (networkinfo != null && networkinfo.isconnected()); } }
注册,并且给予权限
提交任务
package com.example.demo; import android.app.job.jobinfo; import android.app.job.jobscheduler; import android.content.componentname; import android.content.context; import android.content.intent; import android.os.bundle; import android.support.v7.app.appcompatactivity; public class mainactivity extends appcompatactivity { private componentname servicecomponentname; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //开启服务 intent intent = new intent(this, xjobservice.class); startservice(intent); servicecomponentname = new componentname(this, xjobservice.class); //提交10个任务 submittask(); } private void submittask() { jobscheduler scheduler = (jobscheduler) getsystemservice(context.job_scheduler_service); for (int i=0; i<10; i++) { jobinfo jobinfo = new jobinfo.builder(i, servicecomponentname) .setminimumlatency(5000) //任务运行最少延迟时间 .setoverridedeadline(60000) //任务运行最晚期限 .setrequirednetworktype(jobinfo.network_type_any)//有网的时候 .build(); if (scheduler != null) { scheduler.schedule(jobinfo); } } } }