blob: a7442f606f37cc4aac3fb4ea9d7fa8675e8cda39 [file] [log] [blame]
Svetoslavb3038ec2013-02-13 14:39:30 -08001/*
2 * Copyright (C) 2013 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;
18
19import android.app.Activity;
20import android.content.BroadcastReceiver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.os.BatteryManager;
25import android.os.Handler;
26import android.os.Looper;
27import android.os.PowerManager;
28import android.os.PowerManager.WakeLock;
29import android.os.SystemClock;
30import android.os.UserHandle;
31import android.util.Log;
32
33import java.util.Calendar;
34import java.util.TimeZone;
35
36/**
37 * This service observes the device state and when applicable sends
38 * broadcasts at the beginning and at the end of a period during which
39 * observers can perform idle maintenance tasks. Typical use of the
40 * idle maintenance is to perform somehow expensive tasks that can be
41 * postponed to a moment when they will not degrade user experience.
42 *
43 * The current implementation is very simple. The start of a maintenance
44 * window is announced if: the screen is off or showing a dream AND the
45 * battery level is more than twenty percent AND at least one hour passed
46 * since the screen went off or a dream started (i.e. since the last user
47 * activity).
48 *
49 * The end of a maintenance window is announced only if: a start was
50 * announced AND the screen turned on or a dream was stopped.
51 */
52public class IdleMaintenanceService extends BroadcastReceiver {
53
54 private final boolean DEBUG = false;
55
56 private static final String LOG_TAG = IdleMaintenanceService.class.getSimpleName();
57
58 private static final int LAST_USER_ACTIVITY_TIME_INVALID = -1;
59
60 private static final int MIN_IDLE_MAINTENANCE_START_BATTERY_LEVEL = 20; // percent
61
62 private static final long MIN_IDLE_MAINTENANCE_START_USER_INACTIVITY = 60 * 60 * 1000; // 1 hour
63
64 private final Intent mIdleMaintenanceStartIntent =
65 new Intent(Intent.ACTION_IDLE_MAINTENANCE_START);
66
67 private final Intent mIdleMaintenanceEndIntent =
68 new Intent(Intent.ACTION_IDLE_MAINTENANCE_END);
69
70 private final Context mContext;
71
72 private final WakeLock mWakeLock;
73
74 private final Handler mHandler;
75
76 private final Calendar mTempCalendar = Calendar.getInstance();
77
78 private final Calendar mLastIdleMaintenanceStartTime = Calendar.getInstance();
79
80 private long mLastUserActivityElapsedTimeMillis = LAST_USER_ACTIVITY_TIME_INVALID;
81
82 private int mBatteryLevel;
83
84 private boolean mIdleMaintenanceStarted;
85
86 public IdleMaintenanceService(Context context) {
87 mContext = context;
88
89 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
90 mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOG_TAG);
91
92 mHandler = new Handler(mContext.getMainLooper());
93
94 // Move one day back so we can run maintenance the first day after starting.
95 final int prevDayOfYear = mLastIdleMaintenanceStartTime.get(Calendar.DAY_OF_YEAR) - 1;
96 mLastIdleMaintenanceStartTime.set(Calendar.DAY_OF_YEAR, prevDayOfYear);
97
98 register(mContext.getMainLooper());
99 }
100
101 public void register(Looper looper) {
102 IntentFilter intentFilter = new IntentFilter();
103
104 // Battery actions.
105 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
106
107 // Screen actions.
108 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
109 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
110
111 // Dream actions.
112 intentFilter.addAction(Intent.ACTION_DREAMING_STARTED);
113 intentFilter.addAction(Intent.ACTION_DREAMING_STOPPED);
114
115 mContext.registerReceiverAsUser(this, UserHandle.ALL,
116 intentFilter, null, new Handler(looper));
117 }
118
119 private void updateIdleMaintenanceState() {
120 if (mIdleMaintenanceStarted) {
121 // Idle maintenance can be interrupted only by
122 // a change of the device state.
123 if (!deviceStatePermitsIdleMaintenance()) {
124 mIdleMaintenanceStarted = false;
125 sendIdleMaintenanceEndIntent();
126 }
127 } else if (deviceStatePermitsIdleMaintenance()
128 && lastUserActivityPermitsIdleMaintenanceStart()
129 && lastRunPermitsIdleMaintenanceStart()) {
130 mIdleMaintenanceStarted = true;
131 mLastIdleMaintenanceStartTime.setTimeInMillis(System.currentTimeMillis());
132 sendIdleMaintenanceStartIntent();
133 }
134 }
135
136 private void sendIdleMaintenanceStartIntent() {
137 if (DEBUG) {
138 Log.i(LOG_TAG, "Broadcasting " + Intent.ACTION_IDLE_MAINTENANCE_START);
139 }
140 mWakeLock.acquire();
141 mContext.sendOrderedBroadcastAsUser(mIdleMaintenanceStartIntent, UserHandle.ALL,
142 null, this, mHandler, Activity.RESULT_OK, null, null);
143 }
144
145 private void sendIdleMaintenanceEndIntent() {
146 if (DEBUG) {
147 Log.i(LOG_TAG, "Broadcasting " + Intent.ACTION_IDLE_MAINTENANCE_END);
148 }
149 mWakeLock.acquire();
150 mContext.sendOrderedBroadcastAsUser(mIdleMaintenanceEndIntent, UserHandle.ALL,
151 null, this, mHandler, Activity.RESULT_OK, null, null);
152 }
153
154 private boolean deviceStatePermitsIdleMaintenance() {
155 return (mLastUserActivityElapsedTimeMillis != LAST_USER_ACTIVITY_TIME_INVALID
156 && mBatteryLevel > MIN_IDLE_MAINTENANCE_START_BATTERY_LEVEL);
157 }
158
159 private boolean lastUserActivityPermitsIdleMaintenanceStart() {
160 return (SystemClock.elapsedRealtime() - mLastUserActivityElapsedTimeMillis
161 > MIN_IDLE_MAINTENANCE_START_USER_INACTIVITY);
162 }
163
164 private boolean lastRunPermitsIdleMaintenanceStart() {
165 Calendar now = mTempCalendar;
166 // Not setting the Locale since we do not care of locale
167 // specific properties such as the first day of the week.
168 now.setTimeZone(TimeZone.getDefault());
169 now.setTimeInMillis(System.currentTimeMillis());
170
171 Calendar lastRun = mLastIdleMaintenanceStartTime;
172 // Not setting the Locale since we do not care of locale
173 // specific properties such as the first day of the week.
174 lastRun.setTimeZone(TimeZone.getDefault());
175
176 return now.get(Calendar.DAY_OF_YEAR) != lastRun.get(Calendar.DAY_OF_YEAR);
177 }
178
179 @Override
180 public void onReceive(Context context, Intent intent) {
181 if (DEBUG) {
182 Log.i(LOG_TAG, intent.getAction());
183 }
184 String action = intent.getAction();
185 if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
186 final int maxBatteryLevel = intent.getExtras().getInt(BatteryManager.EXTRA_SCALE);
187 final int currBatteryLevel = intent.getExtras().getInt(BatteryManager.EXTRA_LEVEL);
188 mBatteryLevel = (int) (((float) maxBatteryLevel / 100) * currBatteryLevel);
189 } else if (Intent.ACTION_SCREEN_ON.equals(action)
190 || Intent.ACTION_DREAMING_STOPPED.equals(action)) {
191 mLastUserActivityElapsedTimeMillis = LAST_USER_ACTIVITY_TIME_INVALID;
192 } else if (Intent.ACTION_SCREEN_OFF.equals(action)
193 || Intent.ACTION_DREAMING_STARTED.equals(action)) {
194 mLastUserActivityElapsedTimeMillis = SystemClock.elapsedRealtime();
195 } else if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)
196 || Intent.ACTION_IDLE_MAINTENANCE_END.equals(action)) {
197 mWakeLock.release();
198 return;
199 }
200 updateIdleMaintenanceState();
201 }
202}