将Android Lollipop的JobScheduler向后移植至API 10+
jopen
10年前
Android棒棒糖的的jobscheduler反向移植到API 10+。所有的jobscheduler功能已实现。然而,这个库一直没有经过充分测试的,所以我会建议不要在此时在生产中使用。我们不能保证这不会耗尽你的电池或导致设备发生爆炸。
用法
The api is identical to the officialJobScheduler, the only differences will be what you import.
First create a service to run your job.
import me.tatarka.support.job.JobParameters; import me.tatarka.support.job.JobService; /** * Service to handle callbacks from the JobScheduler. Requests scheduled with the JobScheduler * ultimately land on this service's "onStartJob" method. */ public class TestJobService extends JobService { @Override public boolean onStartJob(JobParameters params) { // Start your job in a seperate thread, calling jobFinished(params, needsRescheudle) when you are done. // See the javadoc for more detail. return true; } @Override public boolean onStopJob(JobParameters params) { // Stop the running job, returing true if it needs to be recheduled. // See the javadoc for more detail. return true; }
Then use the JobScheduler
to schedule the job.
import me.tatarka.support.job.JobInfo; import me.tatarka.support.job.JobScheduler; import me.tatarka.support.os.PersistableBundle; // Get an instance of the JobScheduler, this will delegate to the system JobScheduler on api 21+ // and to a custom implementataion on older api levels. JobScheduler jobScheduler = JobScheduler.getInstance(context); // Extras for your job. PersitableBundle extras = new PersitableBundle(); extras.putString("key", "value"); // Construct a new job with your service and some constraints. // See the javadoc for more detail. JobInfo job = new JobInfo.Builder(0 /*jobid*/, new ComponentName(context, TestJobService.class)) .setMinimumLatency(1000) .setOverrideDeadline(2000) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) .setRequiresCharging(true) .setExtras(extras) .build(); jobScheudler.scheduleJob(job);