BackgroundDexOptService.java revision cf1a2f73fc102be2ac7060ac97d4682bb2565ca5
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import android.app.job.JobInfo; 20import android.app.job.JobParameters; 21import android.app.job.JobScheduler; 22import android.app.job.JobService; 23import android.content.ComponentName; 24import android.content.Context; 25import android.os.ServiceManager; 26import android.util.Log; 27 28import java.util.HashSet; 29import java.util.concurrent.atomic.AtomicBoolean; 30 31/** 32 * {@hide} 33 */ 34public class BackgroundDexOptService extends JobService { 35 static final String TAG = "BackgroundDexOptService"; 36 37 static final int BACKGROUND_DEXOPT_JOB = 808; 38 private static ComponentName sDexoptServiceName = new ComponentName( 39 BackgroundDexOptService.class.getPackage().getName(), 40 BackgroundDexOptService.class.getName()); 41 42 final AtomicBoolean mIdleTime = new AtomicBoolean(false); 43 44 public static void schedule(Context context) { 45 JobScheduler js = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); 46 JobInfo job = new JobInfo.Builder(BACKGROUND_DEXOPT_JOB, sDexoptServiceName) 47 .setRequiresDeviceIdle(true) 48 .setRequiresCharging(true) 49 .build(); 50 js.schedule(job); 51 } 52 53 @Override 54 public boolean onStartJob(JobParameters params) { 55 Log.i(TAG, "onIdleStart"); 56 final PackageManagerService pm = 57 (PackageManagerService)ServiceManager.getService("package"); 58 59 if (pm.isStorageLow()) { 60 return false; 61 } 62 final HashSet<String> pkgs = pm.getPackagesThatNeedDexOpt(); 63 if (pkgs == null) { 64 return false; 65 } 66 67 final JobParameters jobParams = params; 68 mIdleTime.set(true); 69 new Thread("BackgroundDexOptService_DexOpter") { 70 @Override 71 public void run() { 72 for (String pkg : pkgs) { 73 if (!mIdleTime.get()) { 74 // stopped while still working, so we need to reschedule 75 schedule(BackgroundDexOptService.this); 76 return; 77 } 78 pm.performDexOpt(pkg, false); 79 } 80 // ran to completion, so we abandon our timeslice and do not reschedule 81 jobFinished(jobParams, false); 82 } 83 }.start(); 84 return true; 85 } 86 87 @Override 88 public boolean onStopJob(JobParameters params) { 89 Log.i(TAG, "onIdleStop"); 90 mIdleTime.set(false); 91 return false; 92 } 93} 94