blob: 280b32941571b2d31d8bda4e1d9f3ead286cb3aa [file] [log] [blame]
Dianne Hackborn7299c412010-03-04 18:41:49 -08001/*
2 * Copyright (C) 2008 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.app.ActivityManagerNative;
21import android.app.AlarmManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080022import android.app.IUiModeManager;
23import android.app.Notification;
24import android.app.NotificationManager;
25import android.app.PendingIntent;
26import android.app.StatusBarManager;
27import android.app.UiModeManager;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -070028import android.content.ActivityNotFoundException;
Dianne Hackborn7299c412010-03-04 18:41:49 -080029import android.content.BroadcastReceiver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.PackageManager;
34import android.content.res.Configuration;
35import android.location.Criteria;
36import android.location.Location;
37import android.location.LocationListener;
38import android.location.LocationManager;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050039import android.os.BatteryManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080040import android.os.Binder;
41import android.os.Bundle;
42import android.os.Handler;
43import android.os.Message;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050044import android.os.PowerManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080045import android.os.RemoteException;
46import android.os.ServiceManager;
Dianne Hackborn57f45032010-06-17 15:49:33 -070047import android.os.SystemClock;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -070048import android.provider.Settings;
Dianne Hackborn7299c412010-03-04 18:41:49 -080049import android.text.format.DateUtils;
50import android.text.format.Time;
51import android.util.Slog;
52
53import java.io.FileDescriptor;
54import java.io.PrintWriter;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010055import java.util.Iterator;
Dianne Hackborn7299c412010-03-04 18:41:49 -080056
57import com.android.internal.R;
58import com.android.internal.app.DisableCarModeActivity;
59
60class UiModeManagerService extends IUiModeManager.Stub {
61 private static final String TAG = UiModeManager.class.getSimpleName();
62 private static final boolean LOG = false;
63
64 private static final String KEY_LAST_UPDATE_INTERVAL = "LAST_UPDATE_INTERVAL";
65
66 private static final int MSG_UPDATE_TWILIGHT = 0;
67 private static final int MSG_ENABLE_LOCATION_UPDATES = 1;
Dianne Hackborn57f45032010-06-17 15:49:33 -070068 private static final int MSG_GET_NEW_LOCATION_UPDATE = 2;
Dianne Hackborn7299c412010-03-04 18:41:49 -080069
Dianne Hackborn57f45032010-06-17 15:49:33 -070070 private static final long LOCATION_UPDATE_MS = 24 * DateUtils.HOUR_IN_MILLIS;
71 private static final long MIN_LOCATION_UPDATE_MS = 30 * DateUtils.MINUTE_IN_MILLIS;
Dianne Hackborn7299c412010-03-04 18:41:49 -080072 private static final float LOCATION_UPDATE_DISTANCE_METER = 1000 * 20;
73 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MIN = 5000;
Dianne Hackborn57f45032010-06-17 15:49:33 -070074 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MAX = 15 * DateUtils.MINUTE_IN_MILLIS;
Dianne Hackborn7299c412010-03-04 18:41:49 -080075 private static final double FACTOR_GMT_OFFSET_LONGITUDE = 1000.0 * 360.0 / DateUtils.DAY_IN_MILLIS;
76
77 private static final String ACTION_UPDATE_NIGHT_MODE = "com.android.server.action.UPDATE_NIGHT_MODE";
78
79 private final Context mContext;
80
81 final Object mLock = new Object();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010082
Dianne Hackborn7299c412010-03-04 18:41:49 -080083 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
84 private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010085
Dianne Hackborn7299c412010-03-04 18:41:49 -080086 private int mNightMode = UiModeManager.MODE_NIGHT_NO;
87 private boolean mCarModeEnabled = false;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050088 private boolean mCharging = false;
89 private final boolean mCarModeKeepsScreenOn;
90 private final boolean mDeskModeKeepsScreenOn;
Dianne Hackborn7299c412010-03-04 18:41:49 -080091
92 private boolean mComputedNightMode;
93 private int mCurUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080094 private int mSetUiMode = 0;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010095
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080096 private boolean mHoldingConfiguration = false;
Dianne Hackborn7299c412010-03-04 18:41:49 -080097 private Configuration mConfiguration = new Configuration();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010098
Dianne Hackborn7299c412010-03-04 18:41:49 -080099 private boolean mSystemReady;
100
101 private NotificationManager mNotificationManager;
102
103 private AlarmManager mAlarmManager;
104
105 private LocationManager mLocationManager;
106 private Location mLocation;
107 private StatusBarManager mStatusBarManager;
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500108 private final PowerManager.WakeLock mWakeLock;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800109
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700110 static Intent buildHomeIntent(String category) {
111 Intent intent = new Intent(Intent.ACTION_MAIN);
112 intent.addCategory(category);
113 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
114 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
115 return intent;
116 }
117
Dianne Hackborn7299c412010-03-04 18:41:49 -0800118 // The broadcast receiver which receives the result of the ordered broadcast sent when
119 // the dock state changes. The original ordered broadcast is sent with an initial result
120 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
121 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
122 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
123 @Override
124 public void onReceive(Context context, Intent intent) {
125 if (getResultCode() != Activity.RESULT_OK) {
Daniel Sandler69a1da42011-11-04 15:08:30 -0400126 if (LOG) {
127 Slog.v(TAG, "Handling broadcast result for action " + intent.getAction()
128 + ": canceled: " + getResultCode());
129 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800130 return;
131 }
132
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700133 final int enableFlags = intent.getIntExtra("enableFlags", 0);
134 final int disableFlags = intent.getIntExtra("disableFlags", 0);
135
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800136 synchronized (mLock) {
137 // Launch a dock activity
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700138 String category = null;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800139 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700140 // Only launch car home when car mode is enabled and the caller
141 // has asked us to switch to it.
142 if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
143 category = Intent.CATEGORY_CAR_DOCK;
144 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800145 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700146 // Only launch car home when desk mode is enabled and the caller
147 // has asked us to switch to it. Currently re-using the car
148 // mode flag since we don't have a formal API for "desk mode".
149 if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
150 category = Intent.CATEGORY_DESK_DOCK;
151 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800152 } else {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700153 // Launch the standard home app if requested.
154 if ((disableFlags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
155 category = Intent.CATEGORY_HOME;
156 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800157 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400158
159 if (LOG) {
160 Slog.v(TAG, String.format(
161 "Handling broadcast result for action %s: enable=0x%08x disable=0x%08x category=%s",
162 intent.getAction(), enableFlags, disableFlags, category));
163 }
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700164
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800165 if (category != null) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700166 // This is the new activity that will serve as home while
167 // we are in care mode.
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700168 Intent homeIntent = buildHomeIntent(category);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700169
170 // Now we are going to be careful about switching the
171 // configuration and starting the activity -- we need to
172 // do this in a specific order under control of the
173 // activity manager, to do it cleanly. So compute the
174 // new config, but don't set it yet, and let the
175 // activity manager take care of both the start and config
176 // change.
177 Configuration newConfig = null;
178 if (mHoldingConfiguration) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700179 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700180 updateConfigurationLocked(false);
181 newConfig = mConfiguration;
182 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800183 try {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700184 ActivityManagerNative.getDefault().startActivityWithConfig(
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700185 null, homeIntent, null, null, 0, null, null, 0, false, false,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700186 newConfig);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700187 mHoldingConfiguration = false;
188 } catch (RemoteException e) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800189 Slog.w(TAG, e.getCause());
190 }
191 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100192
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800193 if (mHoldingConfiguration) {
194 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700195 updateConfigurationLocked(true);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800196 }
197 }
198 }
199 };
200
201 private final BroadcastReceiver mTwilightUpdateReceiver = new BroadcastReceiver() {
202 @Override
203 public void onReceive(Context context, Intent intent) {
204 if (isDoingNightMode() && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
205 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
206 }
207 }
208 };
209
210 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
211 @Override
212 public void onReceive(Context context, Intent intent) {
213 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
214 Intent.EXTRA_DOCK_STATE_UNDOCKED);
215 updateDockState(state);
216 }
217 };
218
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500219 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
220 @Override
221 public void onReceive(Context context, Intent intent) {
222 mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
223 synchronized (mLock) {
224 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700225 updateLocked(0, 0);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500226 }
227 }
228 }
229 };
230
Dianne Hackborn57f45032010-06-17 15:49:33 -0700231 private final BroadcastReceiver mUpdateLocationReceiver = new BroadcastReceiver() {
232 @Override
233 public void onReceive(Context context, Intent intent) {
234 if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())) {
235 if (!intent.getBooleanExtra("state", false)) {
236 // Airplane mode is now off!
237 mHandler.sendEmptyMessage(MSG_GET_NEW_LOCATION_UPDATE);
238 }
239 } else {
240 // Time zone has changed!
241 mHandler.sendEmptyMessage(MSG_GET_NEW_LOCATION_UPDATE);
242 }
243 }
244 };
245
Dianne Hackborn7299c412010-03-04 18:41:49 -0800246 // A LocationListener to initialize the network location provider. The location updates
247 // are handled through the passive location provider.
248 private final LocationListener mEmptyLocationListener = new LocationListener() {
249 public void onLocationChanged(Location location) {
250 }
251
252 public void onProviderDisabled(String provider) {
253 }
254
255 public void onProviderEnabled(String provider) {
256 }
257
258 public void onStatusChanged(String provider, int status, Bundle extras) {
259 }
260 };
261
262 private final LocationListener mLocationListener = new LocationListener() {
263
264 public void onLocationChanged(Location location) {
265 final boolean hasMoved = hasMoved(location);
266 final boolean hasBetterAccuracy = mLocation == null
267 || location.getAccuracy() < mLocation.getAccuracy();
268 if (hasMoved || hasBetterAccuracy) {
269 synchronized (mLock) {
270 mLocation = location;
271 if (hasMoved && isDoingNightMode()
272 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
273 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
274 }
275 }
276 }
277 }
278
279 public void onProviderDisabled(String provider) {
280 }
281
282 public void onProviderEnabled(String provider) {
283 }
284
285 public void onStatusChanged(String provider, int status, Bundle extras) {
286 }
287
288 /*
289 * The user has moved if the accuracy circles of the two locations
290 * don't overlap.
291 */
292 private boolean hasMoved(Location location) {
293 if (location == null) {
294 return false;
295 }
296 if (mLocation == null) {
297 return true;
298 }
299
300 /* if new location is older than the current one, the devices hasn't
301 * moved.
302 */
303 if (location.getTime() < mLocation.getTime()) {
304 return false;
305 }
306
307 /* Get the distance between the two points */
308 float distance = mLocation.distanceTo(location);
309
310 /* Get the total accuracy radius for both locations */
311 float totalAccuracy = mLocation.getAccuracy() + location.getAccuracy();
312
313 /* If the distance is greater than the combined accuracy of the two
314 * points then they can't overlap and hence the user has moved.
315 */
316 return distance >= totalAccuracy;
317 }
318 };
319
320 public UiModeManagerService(Context context) {
321 mContext = context;
322
323 ServiceManager.addService(Context.UI_MODE_SERVICE, this);
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100324
Dianne Hackborn7299c412010-03-04 18:41:49 -0800325 mAlarmManager =
326 (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
327 mLocationManager =
328 (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
329 mContext.registerReceiver(mTwilightUpdateReceiver,
330 new IntentFilter(ACTION_UPDATE_NIGHT_MODE));
331 mContext.registerReceiver(mDockModeReceiver,
332 new IntentFilter(Intent.ACTION_DOCK_EVENT));
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500333 mContext.registerReceiver(mBatteryReceiver,
334 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Dianne Hackborn57f45032010-06-17 15:49:33 -0700335 IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
336 filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
337 mContext.registerReceiver(mUpdateLocationReceiver, filter);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500338
339 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
340 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800341
342 mConfiguration.setToDefaults();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500343
344 mCarModeKeepsScreenOn = (context.getResources().getInteger(
345 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
346 mDeskModeKeepsScreenOn = (context.getResources().getInteger(
347 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700348
349 mNightMode = Settings.Secure.getInt(mContext.getContentResolver(),
350 Settings.Secure.UI_NIGHT_MODE, UiModeManager.MODE_NIGHT_AUTO);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800351 }
352
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700353 public void disableCarMode(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800354 synchronized (mLock) {
355 setCarModeLocked(false);
Mike Lockwood924e1642010-03-05 11:56:53 -0500356 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700357 updateLocked(0, flags);
Mike Lockwood924e1642010-03-05 11:56:53 -0500358 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800359 }
360 }
361
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700362 public void enableCarMode(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800363 synchronized (mLock) {
364 setCarModeLocked(true);
Mike Lockwood924e1642010-03-05 11:56:53 -0500365 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700366 updateLocked(flags, 0);
Mike Lockwood924e1642010-03-05 11:56:53 -0500367 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800368 }
369 }
370
371 public int getCurrentModeType() {
372 synchronized (mLock) {
373 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
374 }
375 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100376
Dianne Hackborn7299c412010-03-04 18:41:49 -0800377 public void setNightMode(int mode) throws RemoteException {
378 synchronized (mLock) {
379 switch (mode) {
380 case UiModeManager.MODE_NIGHT_NO:
381 case UiModeManager.MODE_NIGHT_YES:
382 case UiModeManager.MODE_NIGHT_AUTO:
383 break;
384 default:
385 throw new IllegalArgumentException("Unknown mode: " + mode);
386 }
387 if (!isDoingNightMode()) {
388 return;
389 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100390
Dianne Hackborn7299c412010-03-04 18:41:49 -0800391 if (mNightMode != mode) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700392 long ident = Binder.clearCallingIdentity();
393 Settings.Secure.putInt(mContext.getContentResolver(),
394 Settings.Secure.UI_NIGHT_MODE, mode);
395 Binder.restoreCallingIdentity(ident);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800396 mNightMode = mode;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700397 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800398 }
399 }
400 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100401
Dianne Hackborn7299c412010-03-04 18:41:49 -0800402 public int getNightMode() throws RemoteException {
403 return mNightMode;
404 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100405
Dianne Hackborn7299c412010-03-04 18:41:49 -0800406 void systemReady() {
407 synchronized (mLock) {
408 mSystemReady = true;
409 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700410 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800411 mHandler.sendEmptyMessage(MSG_ENABLE_LOCATION_UPDATES);
412 }
413 }
414
415 boolean isDoingNightMode() {
416 return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
417 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100418
Dianne Hackborn7299c412010-03-04 18:41:49 -0800419 void setCarModeLocked(boolean enabled) {
420 if (mCarModeEnabled != enabled) {
421 mCarModeEnabled = enabled;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800422 }
423 }
424
425 void updateDockState(int newState) {
426 synchronized (mLock) {
427 if (newState != mDockState) {
428 mDockState = newState;
Mike Lockwood924e1642010-03-05 11:56:53 -0500429 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800430 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700431 updateLocked(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800432 }
433 }
434 }
435 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500436
Daniel Sandler69a1da42011-11-04 15:08:30 -0400437 final static boolean isDeskDockState(int state) {
438 switch (state) {
439 case Intent.EXTRA_DOCK_STATE_DESK:
440 case Intent.EXTRA_DOCK_STATE_LE_DESK:
441 case Intent.EXTRA_DOCK_STATE_HE_DESK:
442 return true;
443 default:
444 return false;
445 }
446 }
447
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700448 final void updateConfigurationLocked(boolean sendIt) {
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400449 int uiMode = Configuration.UI_MODE_TYPE_NORMAL;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800450 if (mCarModeEnabled) {
451 uiMode = Configuration.UI_MODE_TYPE_CAR;
Daniel Sandler69a1da42011-11-04 15:08:30 -0400452 } else if (isDeskDockState(mDockState)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800453 uiMode = Configuration.UI_MODE_TYPE_DESK;
454 }
Dianne Hackborn9c9c5322010-03-30 23:12:22 -0700455 if (mCarModeEnabled) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800456 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
457 updateTwilightLocked();
458 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
459 : Configuration.UI_MODE_NIGHT_NO;
460 } else {
461 uiMode |= mNightMode << 4;
462 }
463 } else {
464 // Disabling the car mode clears the night mode.
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400465 uiMode = (uiMode & ~Configuration.UI_MODE_NIGHT_MASK) | Configuration.UI_MODE_NIGHT_NO;
466 }
467
468 if (LOG) {
469 Slog.d(TAG,
470 "updateConfigurationLocked: mDockState=" + mDockState
471 + "; mCarMode=" + mCarModeEnabled
472 + "; mNightMode=" + mNightMode
473 + "; uiMode=" + uiMode);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800474 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100475
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800476 mCurUiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100477
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800478 if (!mHoldingConfiguration && uiMode != mSetUiMode) {
479 mSetUiMode = uiMode;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700480 mConfiguration.uiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100481
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700482 if (sendIt) {
483 try {
484 ActivityManagerNative.getDefault().updateConfiguration(mConfiguration);
485 } catch (RemoteException e) {
486 Slog.w(TAG, "Failure communicating with activity manager", e);
487 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800488 }
489 }
490 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100491
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700492 final void updateLocked(int enableFlags, int disableFlags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800493 long ident = Binder.clearCallingIdentity();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100494
Dianne Hackborn7299c412010-03-04 18:41:49 -0800495 try {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800496 String action = null;
497 String oldAction = null;
498 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
Tobias Haamel780b2602010-03-15 12:54:45 +0100499 adjustStatusBarCarModeLocked();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800500 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
Daniel Sandler69a1da42011-11-04 15:08:30 -0400501 } else if (isDeskDockState(mLastBroadcastState)) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800502 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
503 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100504
Dianne Hackborn7299c412010-03-04 18:41:49 -0800505 if (mCarModeEnabled) {
506 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
507 adjustStatusBarCarModeLocked();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100508
Dianne Hackborn7299c412010-03-04 18:41:49 -0800509 if (oldAction != null) {
510 mContext.sendBroadcast(new Intent(oldAction));
511 }
512 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
513 action = UiModeManager.ACTION_ENTER_CAR_MODE;
514 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400515 } else if (isDeskDockState(mDockState)) {
516 if (!isDeskDockState(mLastBroadcastState)) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800517 if (oldAction != null) {
518 mContext.sendBroadcast(new Intent(oldAction));
519 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400520 mLastBroadcastState = mDockState;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800521 action = UiModeManager.ACTION_ENTER_DESK_MODE;
522 }
523 } else {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800524 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
525 action = oldAction;
526 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100527
Dianne Hackborn7299c412010-03-04 18:41:49 -0800528 if (action != null) {
Daniel Sandler69a1da42011-11-04 15:08:30 -0400529 if (LOG) {
530 Slog.v(TAG, String.format(
531 "updateLocked: preparing broadcast: action=%s enable=0x%08x disable=0x%08x",
532 action, enableFlags, disableFlags));
533 }
534
Dianne Hackborn7299c412010-03-04 18:41:49 -0800535 // Send the ordered broadcast; the result receiver will receive after all
536 // broadcasts have been sent. If any broadcast receiver changes the result
537 // code from the initial value of RESULT_OK, then the result receiver will
538 // not launch the corresponding dock application. This gives apps a chance
539 // to override the behavior and stay in their app even when the device is
540 // placed into a dock.
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700541 Intent intent = new Intent(action);
542 intent.putExtra("enableFlags", enableFlags);
543 intent.putExtra("disableFlags", disableFlags);
544 mContext.sendOrderedBroadcast(intent, null,
Dianne Hackborn7299c412010-03-04 18:41:49 -0800545 mResultReceiver, null, Activity.RESULT_OK, null, null);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800546 // Attempting to make this transition a little more clean, we are going
547 // to hold off on doing a configuration change until we have finished
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700548 // the broadcast and started the home activity.
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800549 mHoldingConfiguration = true;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700550 } else {
551 Intent homeIntent = null;
552 if (mCarModeEnabled) {
553 if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
554 homeIntent = buildHomeIntent(Intent.CATEGORY_CAR_DOCK);
555 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400556 } else if (isDeskDockState(mDockState)) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700557 if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
558 homeIntent = buildHomeIntent(Intent.CATEGORY_DESK_DOCK);
559 }
560 } else {
561 if ((disableFlags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
562 homeIntent = buildHomeIntent(Intent.CATEGORY_HOME);
563 }
564 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400565
566 if (LOG) {
567 Slog.v(TAG, "updateLocked: null action, mDockState="
568 + mDockState +", firing homeIntent: " + homeIntent);
569 }
570
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700571 if (homeIntent != null) {
572 try {
573 mContext.startActivity(homeIntent);
574 } catch (ActivityNotFoundException e) {
575 }
576 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800577 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100578
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700579 updateConfigurationLocked(true);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500580
581 // keep screen on when charging and in car mode
582 boolean keepScreenOn = mCharging &&
583 ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
584 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
585 if (keepScreenOn != mWakeLock.isHeld()) {
586 if (keepScreenOn) {
587 mWakeLock.acquire();
588 } else {
589 mWakeLock.release();
590 }
591 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800592 } finally {
593 Binder.restoreCallingIdentity(ident);
594 }
595 }
596
597 private void adjustStatusBarCarModeLocked() {
598 if (mStatusBarManager == null) {
599 mStatusBarManager = (StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
600 }
601
Joe Onorato089de882010-04-12 08:18:45 -0700602 // Fear not: StatusBarManagerService manages a list of requests to disable
Dianne Hackborn7299c412010-03-04 18:41:49 -0800603 // features of the status bar; these are ORed together to form the
604 // active disabled list. So if (for example) the device is locked and
605 // the status bar should be totally disabled, the calls below will
606 // have no effect until the device is unlocked.
607 if (mStatusBarManager != null) {
608 mStatusBarManager.disable(mCarModeEnabled
609 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
610 : StatusBarManager.DISABLE_NONE);
611 }
612
613 if (mNotificationManager == null) {
614 mNotificationManager = (NotificationManager)
615 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
616 }
617
618 if (mNotificationManager != null) {
619 if (mCarModeEnabled) {
620 Intent carModeOffIntent = new Intent(mContext, DisableCarModeActivity.class);
621
622 Notification n = new Notification();
623 n.icon = R.drawable.stat_notify_car_mode;
624 n.defaults = Notification.DEFAULT_LIGHTS;
625 n.flags = Notification.FLAG_ONGOING_EVENT;
626 n.when = 0;
627 n.setLatestEventInfo(
628 mContext,
629 mContext.getString(R.string.car_mode_disable_notification_title),
630 mContext.getString(R.string.car_mode_disable_notification_message),
631 PendingIntent.getActivity(mContext, 0, carModeOffIntent, 0));
632 mNotificationManager.notify(0, n);
633 } else {
634 mNotificationManager.cancel(0);
635 }
636 }
637 }
638
639 private final Handler mHandler = new Handler() {
640
641 boolean mPassiveListenerEnabled;
642 boolean mNetworkListenerEnabled;
Dianne Hackborn57f45032010-06-17 15:49:33 -0700643 boolean mDidFirstInit;
644 long mLastNetworkRegisterTime = -MIN_LOCATION_UPDATE_MS;
645
Dianne Hackborn7299c412010-03-04 18:41:49 -0800646 @Override
647 public void handleMessage(Message msg) {
648 switch (msg.what) {
649 case MSG_UPDATE_TWILIGHT:
650 synchronized (mLock) {
651 if (isDoingNightMode() && mLocation != null
652 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
653 updateTwilightLocked();
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700654 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800655 }
656 }
657 break;
Dianne Hackborn57f45032010-06-17 15:49:33 -0700658 case MSG_GET_NEW_LOCATION_UPDATE:
659 if (!mNetworkListenerEnabled) {
660 // Don't do anything -- we are still trying to get a
661 // location.
662 return;
663 }
664 if ((mLastNetworkRegisterTime+MIN_LOCATION_UPDATE_MS)
665 >= SystemClock.elapsedRealtime()) {
666 // Don't do anything -- it hasn't been long enough
667 // since we last requested an update.
668 return;
669 }
670
671 // Unregister the current location monitor, so we can
672 // register a new one for it to get an immediate update.
673 mNetworkListenerEnabled = false;
674 mLocationManager.removeUpdates(mEmptyLocationListener);
675
676 // Fall through to re-register listener.
Dianne Hackborn7299c412010-03-04 18:41:49 -0800677 case MSG_ENABLE_LOCATION_UPDATES:
678 // enable network provider to receive at least location updates for a given
679 // distance.
680 boolean networkLocationEnabled;
681 try {
682 networkLocationEnabled =
683 mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
684 } catch (Exception e) {
685 // we may get IllegalArgumentException if network location provider
686 // does not exist or is not yet installed.
687 networkLocationEnabled = false;
688 }
689 if (!mNetworkListenerEnabled && networkLocationEnabled) {
690 mNetworkListenerEnabled = true;
Dianne Hackborn57f45032010-06-17 15:49:33 -0700691 mLastNetworkRegisterTime = SystemClock.elapsedRealtime();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800692 mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
693 LOCATION_UPDATE_MS, 0, mEmptyLocationListener);
694
Dianne Hackborn57f45032010-06-17 15:49:33 -0700695 if (!mDidFirstInit) {
696 mDidFirstInit = true;
697 if (mLocation == null) {
698 retrieveLocation();
699 }
700 synchronized (mLock) {
701 if (isDoingNightMode() && mLocation != null
702 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
703 updateTwilightLocked();
704 updateLocked(0, 0);
705 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800706 }
707 }
708 }
709 // enable passive provider to receive updates from location fixes (gps
710 // and network).
711 boolean passiveLocationEnabled;
712 try {
713 passiveLocationEnabled =
714 mLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
715 } catch (Exception e) {
716 // we may get IllegalArgumentException if passive location provider
717 // does not exist or is not yet installed.
718 passiveLocationEnabled = false;
719 }
720 if (!mPassiveListenerEnabled && passiveLocationEnabled) {
721 mPassiveListenerEnabled = true;
722 mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
723 0, LOCATION_UPDATE_DISTANCE_METER , mLocationListener);
724 }
725 if (!(mNetworkListenerEnabled && mPassiveListenerEnabled)) {
726 long interval = msg.getData().getLong(KEY_LAST_UPDATE_INTERVAL);
727 interval *= 1.5;
728 if (interval == 0) {
729 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MIN;
730 } else if (interval > LOCATION_UPDATE_ENABLE_INTERVAL_MAX) {
731 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MAX;
732 }
733 Bundle bundle = new Bundle();
734 bundle.putLong(KEY_LAST_UPDATE_INTERVAL, interval);
735 Message newMsg = mHandler.obtainMessage(MSG_ENABLE_LOCATION_UPDATES);
736 newMsg.setData(bundle);
737 mHandler.sendMessageDelayed(newMsg, interval);
738 }
739 break;
740 }
741 }
742
743 private void retrieveLocation() {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100744 Location location = null;
745 final Iterator<String> providers =
746 mLocationManager.getProviders(new Criteria(), true).iterator();
747 while (providers.hasNext()) {
748 final Location lastKnownLocation =
749 mLocationManager.getLastKnownLocation(providers.next());
750 // pick the most recent location
751 if (location == null || (lastKnownLocation != null &&
752 location.getTime() < lastKnownLocation.getTime())) {
753 location = lastKnownLocation;
754 }
755 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800756 // In the case there is no location available (e.g. GPS fix or network location
757 // is not available yet), the longitude of the location is estimated using the timezone,
758 // latitude and accuracy are set to get a good average.
759 if (location == null) {
760 Time currentTime = new Time();
761 currentTime.set(System.currentTimeMillis());
762 double lngOffset = FACTOR_GMT_OFFSET_LONGITUDE *
763 (currentTime.gmtoff - (currentTime.isDst > 0 ? 3600 : 0));
764 location = new Location("fake");
765 location.setLongitude(lngOffset);
766 location.setLatitude(0);
767 location.setAccuracy(417000.0f);
768 location.setTime(System.currentTimeMillis());
769 }
770 synchronized (mLock) {
771 mLocation = location;
772 }
773 }
774 };
775
776 void updateTwilightLocked() {
777 if (mLocation == null) {
778 return;
779 }
780 final long currentTime = System.currentTimeMillis();
781 boolean nightMode;
782 // calculate current twilight
783 TwilightCalculator tw = new TwilightCalculator();
784 tw.calculateTwilight(currentTime,
785 mLocation.getLatitude(), mLocation.getLongitude());
786 if (tw.mState == TwilightCalculator.DAY) {
787 nightMode = false;
788 } else {
789 nightMode = true;
790 }
791
792 // schedule next update
793 long nextUpdate = 0;
794 if (tw.mSunrise == -1 || tw.mSunset == -1) {
795 // In the case the day or night never ends the update is scheduled 12 hours later.
796 nextUpdate = currentTime + 12 * DateUtils.HOUR_IN_MILLIS;
797 } else {
798 final int mLastTwilightState = tw.mState;
799 // add some extra time to be on the save side.
800 nextUpdate += DateUtils.MINUTE_IN_MILLIS;
801 if (currentTime > tw.mSunset) {
802 // next update should be on the following day
803 tw.calculateTwilight(currentTime
804 + DateUtils.DAY_IN_MILLIS, mLocation.getLatitude(),
805 mLocation.getLongitude());
806 }
807
808 if (mLastTwilightState == TwilightCalculator.NIGHT) {
809 nextUpdate += tw.mSunrise;
810 } else {
811 nextUpdate += tw.mSunset;
812 }
813 }
814
815 Intent updateIntent = new Intent(ACTION_UPDATE_NIGHT_MODE);
816 PendingIntent pendingIntent =
817 PendingIntent.getBroadcast(mContext, 0, updateIntent, 0);
818 mAlarmManager.cancel(pendingIntent);
819 mAlarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdate, pendingIntent);
820
821 mComputedNightMode = nightMode;
822 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100823
Dianne Hackborn7299c412010-03-04 18:41:49 -0800824 @Override
825 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
826 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
827 != PackageManager.PERMISSION_GRANTED) {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100828
Dianne Hackborn7299c412010-03-04 18:41:49 -0800829 pw.println("Permission Denial: can't dump uimode service from from pid="
830 + Binder.getCallingPid()
831 + ", uid=" + Binder.getCallingUid());
832 return;
833 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100834
Dianne Hackborn7299c412010-03-04 18:41:49 -0800835 synchronized (mLock) {
836 pw.println("Current UI Mode Service state:");
837 pw.print(" mDockState="); pw.print(mDockState);
838 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
839 pw.print(" mNightMode="); pw.print(mNightMode);
840 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
841 pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
842 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800843 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
844 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800845 pw.print(" mSystemReady="); pw.println(mSystemReady);
846 if (mLocation != null) {
847 pw.print(" mLocation="); pw.println(mLocation);
848 }
849 }
850 }
851}