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.settings.fuelgauge.batterytip; 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.Context; 25 import android.support.annotation.VisibleForTesting; 26 import android.util.Log; 27 28 import com.android.settings.R; 29 import com.android.settingslib.utils.ThreadUtils; 30 31 import java.util.concurrent.TimeUnit; 32 33 /** A JobService to clean up obsolete data in anomaly database */ 34 public class AnomalyCleanupJobService extends JobService { 35 private static final String TAG = "AnomalyCleanUpJobService"; 36 37 @VisibleForTesting 38 static final long CLEAN_UP_FREQUENCY_MS = TimeUnit.DAYS.toMillis(1); 39 40 public static void scheduleCleanUp(Context context) { 41 final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class); 42 43 final ComponentName component = new ComponentName(context, AnomalyCleanupJobService.class); 44 final JobInfo.Builder jobBuilder = 45 new JobInfo.Builder(R.integer.job_anomaly_clean_up, component) 46 .setPeriodic(CLEAN_UP_FREQUENCY_MS) 47 .setRequiresDeviceIdle(true) 48 .setRequiresCharging(true) 49 .setPersisted(true); 50 final JobInfo pending = jobScheduler.getPendingJob(R.integer.job_anomaly_clean_up); 51 52 // Don't schedule it if it already exists, to make sure it runs periodically even after 53 // reboot 54 if (pending == null && jobScheduler.schedule(jobBuilder.build()) 55 != JobScheduler.RESULT_SUCCESS) { 56 Log.i(TAG, "Anomaly clean up job service schedule failed."); 57 } 58 } 59 60 @Override 61 public boolean onStartJob(JobParameters params) { 62 final BatteryDatabaseManager batteryDatabaseManager = BatteryDatabaseManager 63 .getInstance(this); 64 final BatteryTipPolicy policy = new BatteryTipPolicy(this); 65 ThreadUtils.postOnBackgroundThread(() -> { 66 batteryDatabaseManager.deleteAllAnomaliesBeforeTimeStamp( 67 System.currentTimeMillis() - TimeUnit.DAYS.toMillis( 68 policy.dataHistoryRetainDay)); 69 jobFinished(params, false /* wantsReschedule */); 70 }); 71 72 return true; 73 } 74 75 @Override 76 public boolean onStopJob(JobParameters jobParameters) { 77 return false; 78 } 79 } 80