1 /* 2 * Copyright (C) 2018 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 17 package com.android.providers.media; 18 19 import android.app.job.JobInfo; 20 import android.app.job.JobParameters; 21 import android.app.job.JobScheduler; 22 import android.app.job.JobService; 23 import android.content.ComponentName; 24 import android.content.ContentProviderClient; 25 import android.content.Context; 26 import android.os.CancellationSignal; 27 import android.os.OperationCanceledException; 28 import android.provider.MediaStore; 29 30 import java.util.concurrent.TimeUnit; 31 32 public class IdleService extends JobService { 33 private static final int IDLE_JOB_ID = -200; 34 35 private CancellationSignal mSignal; 36 37 @Override onStartJob(JobParameters params)38 public boolean onStartJob(JobParameters params) { 39 mSignal = new CancellationSignal(); 40 new Thread(() -> { 41 try (ContentProviderClient cpc = getContentResolver() 42 .acquireContentProviderClient(MediaStore.AUTHORITY)) { 43 ((MediaProvider) cpc.getLocalContentProvider()).onIdleMaintenance(mSignal); 44 } catch (OperationCanceledException ignored) { 45 } 46 jobFinished(params, false); 47 }).start(); 48 return true; 49 } 50 51 @Override onStopJob(JobParameters params)52 public boolean onStopJob(JobParameters params) { 53 mSignal.cancel(); 54 try (ContentProviderClient cpc = getContentResolver() 55 .acquireContentProviderClient(MediaStore.AUTHORITY)) { 56 ((MediaProvider) cpc.getLocalContentProvider()).onIdleMaintenanceStopped(); 57 } catch (OperationCanceledException ignored) { 58 } 59 return false; 60 } 61 scheduleIdlePass(Context context)62 public static void scheduleIdlePass(Context context) { 63 final JobScheduler scheduler = context.getSystemService(JobScheduler.class); 64 if (scheduler.getPendingJob(IDLE_JOB_ID) == null) { 65 final JobInfo job = new JobInfo.Builder(IDLE_JOB_ID, 66 new ComponentName(context, IdleService.class)) 67 .setPeriodic(TimeUnit.HOURS.toMillis(24)) 68 .setRequiresCharging(true) 69 .setRequiresDeviceIdle(true) 70 .build(); 71 scheduler.schedule(job); 72 } 73 } 74 } 75