blob: c5c2901745e49d3c54db4fb3d7929c18a987b378 [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
Daniel Sandler11ddf532011-11-16 11:10:03 -080066 // Enable launching of applications when entering the dock.
67 private static final boolean ENABLE_LAUNCH_CAR_DOCK_APP = true;
68 private static final boolean ENABLE_LAUNCH_DESK_DOCK_APP = false;
69
Dianne Hackborn7299c412010-03-04 18:41:49 -080070 private static final int MSG_UPDATE_TWILIGHT = 0;
71 private static final int MSG_ENABLE_LOCATION_UPDATES = 1;
Dianne Hackborn57f45032010-06-17 15:49:33 -070072 private static final int MSG_GET_NEW_LOCATION_UPDATE = 2;
Dianne Hackborn7299c412010-03-04 18:41:49 -080073
Dianne Hackborn57f45032010-06-17 15:49:33 -070074 private static final long LOCATION_UPDATE_MS = 24 * DateUtils.HOUR_IN_MILLIS;
75 private static final long MIN_LOCATION_UPDATE_MS = 30 * DateUtils.MINUTE_IN_MILLIS;
Dianne Hackborn7299c412010-03-04 18:41:49 -080076 private static final float LOCATION_UPDATE_DISTANCE_METER = 1000 * 20;
77 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MIN = 5000;
Dianne Hackborn57f45032010-06-17 15:49:33 -070078 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MAX = 15 * DateUtils.MINUTE_IN_MILLIS;
Dianne Hackborn7299c412010-03-04 18:41:49 -080079 private static final double FACTOR_GMT_OFFSET_LONGITUDE = 1000.0 * 360.0 / DateUtils.DAY_IN_MILLIS;
80
81 private static final String ACTION_UPDATE_NIGHT_MODE = "com.android.server.action.UPDATE_NIGHT_MODE";
82
83 private final Context mContext;
84
85 final Object mLock = new Object();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010086
Dianne Hackborn7299c412010-03-04 18:41:49 -080087 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
88 private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010089
Dianne Hackborn7299c412010-03-04 18:41:49 -080090 private int mNightMode = UiModeManager.MODE_NIGHT_NO;
91 private boolean mCarModeEnabled = false;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050092 private boolean mCharging = false;
Joe Onorato44fcb832011-12-14 20:59:30 -080093 private final int mDefaultUiModeType;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050094 private final boolean mCarModeKeepsScreenOn;
95 private final boolean mDeskModeKeepsScreenOn;
Dianne Hackborn7299c412010-03-04 18:41:49 -080096
97 private boolean mComputedNightMode;
98 private int mCurUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080099 private int mSetUiMode = 0;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100100
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800101 private boolean mHoldingConfiguration = false;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800102 private Configuration mConfiguration = new Configuration();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100103
Dianne Hackborn7299c412010-03-04 18:41:49 -0800104 private boolean mSystemReady;
105
106 private NotificationManager mNotificationManager;
107
108 private AlarmManager mAlarmManager;
109
110 private LocationManager mLocationManager;
111 private Location mLocation;
112 private StatusBarManager mStatusBarManager;
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500113 private final PowerManager.WakeLock mWakeLock;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800114
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700115 static Intent buildHomeIntent(String category) {
116 Intent intent = new Intent(Intent.ACTION_MAIN);
117 intent.addCategory(category);
118 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
119 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
120 return intent;
121 }
122
Dianne Hackborn7299c412010-03-04 18:41:49 -0800123 // The broadcast receiver which receives the result of the ordered broadcast sent when
124 // the dock state changes. The original ordered broadcast is sent with an initial result
125 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
126 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
127 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
128 @Override
129 public void onReceive(Context context, Intent intent) {
130 if (getResultCode() != Activity.RESULT_OK) {
Daniel Sandler69a1da42011-11-04 15:08:30 -0400131 if (LOG) {
132 Slog.v(TAG, "Handling broadcast result for action " + intent.getAction()
133 + ": canceled: " + getResultCode());
134 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800135 return;
136 }
137
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700138 final int enableFlags = intent.getIntExtra("enableFlags", 0);
139 final int disableFlags = intent.getIntExtra("disableFlags", 0);
140
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800141 synchronized (mLock) {
142 // Launch a dock activity
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700143 String category = null;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800144 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700145 // Only launch car home when car mode is enabled and the caller
146 // has asked us to switch to it.
Daniel Sandler11ddf532011-11-16 11:10:03 -0800147 if (ENABLE_LAUNCH_CAR_DOCK_APP
148 && (enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700149 category = Intent.CATEGORY_CAR_DOCK;
150 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800151 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700152 // Only launch car home when desk mode is enabled and the caller
153 // has asked us to switch to it. Currently re-using the car
154 // mode flag since we don't have a formal API for "desk mode".
Daniel Sandler11ddf532011-11-16 11:10:03 -0800155 if (ENABLE_LAUNCH_DESK_DOCK_APP
156 && (enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700157 category = Intent.CATEGORY_DESK_DOCK;
158 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800159 } else {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700160 // Launch the standard home app if requested.
161 if ((disableFlags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
162 category = Intent.CATEGORY_HOME;
163 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800164 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400165
166 if (LOG) {
167 Slog.v(TAG, String.format(
168 "Handling broadcast result for action %s: enable=0x%08x disable=0x%08x category=%s",
169 intent.getAction(), enableFlags, disableFlags, category));
170 }
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700171
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800172 if (category != null) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700173 // This is the new activity that will serve as home while
174 // we are in care mode.
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700175 Intent homeIntent = buildHomeIntent(category);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700176
177 // Now we are going to be careful about switching the
178 // configuration and starting the activity -- we need to
179 // do this in a specific order under control of the
180 // activity manager, to do it cleanly. So compute the
181 // new config, but don't set it yet, and let the
182 // activity manager take care of both the start and config
183 // change.
184 Configuration newConfig = null;
185 if (mHoldingConfiguration) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700186 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700187 updateConfigurationLocked(false);
188 newConfig = mConfiguration;
189 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800190 try {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700191 ActivityManagerNative.getDefault().startActivityWithConfig(
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700192 null, homeIntent, null, null, 0, null, null, 0, false, false,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700193 newConfig);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700194 mHoldingConfiguration = false;
195 } catch (RemoteException e) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800196 Slog.w(TAG, e.getCause());
197 }
198 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100199
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800200 if (mHoldingConfiguration) {
201 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700202 updateConfigurationLocked(true);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800203 }
204 }
205 }
206 };
207
208 private final BroadcastReceiver mTwilightUpdateReceiver = new BroadcastReceiver() {
209 @Override
210 public void onReceive(Context context, Intent intent) {
211 if (isDoingNightMode() && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
212 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
213 }
214 }
215 };
216
217 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
218 @Override
219 public void onReceive(Context context, Intent intent) {
220 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
221 Intent.EXTRA_DOCK_STATE_UNDOCKED);
222 updateDockState(state);
223 }
224 };
225
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500226 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
227 @Override
228 public void onReceive(Context context, Intent intent) {
229 mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
230 synchronized (mLock) {
231 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700232 updateLocked(0, 0);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500233 }
234 }
235 }
236 };
237
Dianne Hackborn57f45032010-06-17 15:49:33 -0700238 private final BroadcastReceiver mUpdateLocationReceiver = new BroadcastReceiver() {
239 @Override
240 public void onReceive(Context context, Intent intent) {
241 if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())) {
242 if (!intent.getBooleanExtra("state", false)) {
243 // Airplane mode is now off!
244 mHandler.sendEmptyMessage(MSG_GET_NEW_LOCATION_UPDATE);
245 }
246 } else {
247 // Time zone has changed!
248 mHandler.sendEmptyMessage(MSG_GET_NEW_LOCATION_UPDATE);
249 }
250 }
251 };
252
Dianne Hackborn7299c412010-03-04 18:41:49 -0800253 // A LocationListener to initialize the network location provider. The location updates
254 // are handled through the passive location provider.
255 private final LocationListener mEmptyLocationListener = new LocationListener() {
256 public void onLocationChanged(Location location) {
257 }
258
259 public void onProviderDisabled(String provider) {
260 }
261
262 public void onProviderEnabled(String provider) {
263 }
264
265 public void onStatusChanged(String provider, int status, Bundle extras) {
266 }
267 };
268
269 private final LocationListener mLocationListener = new LocationListener() {
270
271 public void onLocationChanged(Location location) {
272 final boolean hasMoved = hasMoved(location);
273 final boolean hasBetterAccuracy = mLocation == null
274 || location.getAccuracy() < mLocation.getAccuracy();
275 if (hasMoved || hasBetterAccuracy) {
276 synchronized (mLock) {
277 mLocation = location;
278 if (hasMoved && isDoingNightMode()
279 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
280 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
281 }
282 }
283 }
284 }
285
286 public void onProviderDisabled(String provider) {
287 }
288
289 public void onProviderEnabled(String provider) {
290 }
291
292 public void onStatusChanged(String provider, int status, Bundle extras) {
293 }
294
295 /*
296 * The user has moved if the accuracy circles of the two locations
297 * don't overlap.
298 */
299 private boolean hasMoved(Location location) {
300 if (location == null) {
301 return false;
302 }
303 if (mLocation == null) {
304 return true;
305 }
306
307 /* if new location is older than the current one, the devices hasn't
308 * moved.
309 */
310 if (location.getTime() < mLocation.getTime()) {
311 return false;
312 }
313
314 /* Get the distance between the two points */
315 float distance = mLocation.distanceTo(location);
316
317 /* Get the total accuracy radius for both locations */
318 float totalAccuracy = mLocation.getAccuracy() + location.getAccuracy();
319
320 /* If the distance is greater than the combined accuracy of the two
321 * points then they can't overlap and hence the user has moved.
322 */
323 return distance >= totalAccuracy;
324 }
325 };
326
327 public UiModeManagerService(Context context) {
328 mContext = context;
329
330 ServiceManager.addService(Context.UI_MODE_SERVICE, this);
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100331
Dianne Hackborn7299c412010-03-04 18:41:49 -0800332 mAlarmManager =
333 (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
334 mLocationManager =
335 (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
336 mContext.registerReceiver(mTwilightUpdateReceiver,
337 new IntentFilter(ACTION_UPDATE_NIGHT_MODE));
338 mContext.registerReceiver(mDockModeReceiver,
339 new IntentFilter(Intent.ACTION_DOCK_EVENT));
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500340 mContext.registerReceiver(mBatteryReceiver,
341 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Dianne Hackborn57f45032010-06-17 15:49:33 -0700342 IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
343 filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
344 mContext.registerReceiver(mUpdateLocationReceiver, filter);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500345
346 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
347 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800348
349 mConfiguration.setToDefaults();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500350
Joe Onorato44fcb832011-12-14 20:59:30 -0800351 mDefaultUiModeType = context.getResources().getInteger(
352 com.android.internal.R.integer.config_defaultUiModeType);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500353 mCarModeKeepsScreenOn = (context.getResources().getInteger(
354 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
355 mDeskModeKeepsScreenOn = (context.getResources().getInteger(
356 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700357
358 mNightMode = Settings.Secure.getInt(mContext.getContentResolver(),
359 Settings.Secure.UI_NIGHT_MODE, UiModeManager.MODE_NIGHT_AUTO);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800360 }
361
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700362 public void disableCarMode(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800363 synchronized (mLock) {
364 setCarModeLocked(false);
Mike Lockwood924e1642010-03-05 11:56:53 -0500365 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700366 updateLocked(0, flags);
Mike Lockwood924e1642010-03-05 11:56:53 -0500367 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800368 }
369 }
370
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700371 public void enableCarMode(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800372 synchronized (mLock) {
373 setCarModeLocked(true);
Mike Lockwood924e1642010-03-05 11:56:53 -0500374 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700375 updateLocked(flags, 0);
Mike Lockwood924e1642010-03-05 11:56:53 -0500376 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800377 }
378 }
379
380 public int getCurrentModeType() {
381 synchronized (mLock) {
382 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
383 }
384 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100385
Dianne Hackborn7299c412010-03-04 18:41:49 -0800386 public void setNightMode(int mode) throws RemoteException {
387 synchronized (mLock) {
388 switch (mode) {
389 case UiModeManager.MODE_NIGHT_NO:
390 case UiModeManager.MODE_NIGHT_YES:
391 case UiModeManager.MODE_NIGHT_AUTO:
392 break;
393 default:
394 throw new IllegalArgumentException("Unknown mode: " + mode);
395 }
396 if (!isDoingNightMode()) {
397 return;
398 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100399
Dianne Hackborn7299c412010-03-04 18:41:49 -0800400 if (mNightMode != mode) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700401 long ident = Binder.clearCallingIdentity();
402 Settings.Secure.putInt(mContext.getContentResolver(),
403 Settings.Secure.UI_NIGHT_MODE, mode);
404 Binder.restoreCallingIdentity(ident);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800405 mNightMode = mode;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700406 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800407 }
408 }
409 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100410
Dianne Hackborn7299c412010-03-04 18:41:49 -0800411 public int getNightMode() throws RemoteException {
412 return mNightMode;
413 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100414
Dianne Hackborn7299c412010-03-04 18:41:49 -0800415 void systemReady() {
416 synchronized (mLock) {
417 mSystemReady = true;
418 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700419 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800420 mHandler.sendEmptyMessage(MSG_ENABLE_LOCATION_UPDATES);
421 }
422 }
423
424 boolean isDoingNightMode() {
425 return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
426 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100427
Dianne Hackborn7299c412010-03-04 18:41:49 -0800428 void setCarModeLocked(boolean enabled) {
429 if (mCarModeEnabled != enabled) {
430 mCarModeEnabled = enabled;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800431 }
432 }
433
434 void updateDockState(int newState) {
435 synchronized (mLock) {
436 if (newState != mDockState) {
437 mDockState = newState;
Mike Lockwood924e1642010-03-05 11:56:53 -0500438 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800439 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700440 updateLocked(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800441 }
442 }
443 }
444 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500445
Daniel Sandler69a1da42011-11-04 15:08:30 -0400446 final static boolean isDeskDockState(int state) {
447 switch (state) {
448 case Intent.EXTRA_DOCK_STATE_DESK:
449 case Intent.EXTRA_DOCK_STATE_LE_DESK:
450 case Intent.EXTRA_DOCK_STATE_HE_DESK:
451 return true;
452 default:
453 return false;
454 }
455 }
456
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700457 final void updateConfigurationLocked(boolean sendIt) {
Joe Onorato44fcb832011-12-14 20:59:30 -0800458 int uiMode = mDefaultUiModeType;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800459 if (mCarModeEnabled) {
460 uiMode = Configuration.UI_MODE_TYPE_CAR;
Daniel Sandler69a1da42011-11-04 15:08:30 -0400461 } else if (isDeskDockState(mDockState)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800462 uiMode = Configuration.UI_MODE_TYPE_DESK;
463 }
Dianne Hackborn9c9c5322010-03-30 23:12:22 -0700464 if (mCarModeEnabled) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800465 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
466 updateTwilightLocked();
467 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
468 : Configuration.UI_MODE_NIGHT_NO;
469 } else {
470 uiMode |= mNightMode << 4;
471 }
472 } else {
473 // Disabling the car mode clears the night mode.
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400474 uiMode = (uiMode & ~Configuration.UI_MODE_NIGHT_MASK) | Configuration.UI_MODE_NIGHT_NO;
475 }
476
477 if (LOG) {
478 Slog.d(TAG,
479 "updateConfigurationLocked: mDockState=" + mDockState
480 + "; mCarMode=" + mCarModeEnabled
481 + "; mNightMode=" + mNightMode
482 + "; uiMode=" + uiMode);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800483 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100484
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800485 mCurUiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100486
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800487 if (!mHoldingConfiguration && uiMode != mSetUiMode) {
488 mSetUiMode = uiMode;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700489 mConfiguration.uiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100490
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700491 if (sendIt) {
492 try {
493 ActivityManagerNative.getDefault().updateConfiguration(mConfiguration);
494 } catch (RemoteException e) {
495 Slog.w(TAG, "Failure communicating with activity manager", e);
496 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800497 }
498 }
499 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100500
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700501 final void updateLocked(int enableFlags, int disableFlags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800502 long ident = Binder.clearCallingIdentity();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100503
Dianne Hackborn7299c412010-03-04 18:41:49 -0800504 try {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800505 String action = null;
506 String oldAction = null;
507 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
Tobias Haamel780b2602010-03-15 12:54:45 +0100508 adjustStatusBarCarModeLocked();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800509 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
Daniel Sandler69a1da42011-11-04 15:08:30 -0400510 } else if (isDeskDockState(mLastBroadcastState)) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800511 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
512 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100513
Dianne Hackborn7299c412010-03-04 18:41:49 -0800514 if (mCarModeEnabled) {
515 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
516 adjustStatusBarCarModeLocked();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100517
Dianne Hackborn7299c412010-03-04 18:41:49 -0800518 if (oldAction != null) {
519 mContext.sendBroadcast(new Intent(oldAction));
520 }
521 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
522 action = UiModeManager.ACTION_ENTER_CAR_MODE;
523 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400524 } else if (isDeskDockState(mDockState)) {
525 if (!isDeskDockState(mLastBroadcastState)) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800526 if (oldAction != null) {
527 mContext.sendBroadcast(new Intent(oldAction));
528 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400529 mLastBroadcastState = mDockState;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800530 action = UiModeManager.ACTION_ENTER_DESK_MODE;
531 }
532 } else {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800533 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
534 action = oldAction;
535 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100536
Dianne Hackborn7299c412010-03-04 18:41:49 -0800537 if (action != null) {
Daniel Sandler69a1da42011-11-04 15:08:30 -0400538 if (LOG) {
539 Slog.v(TAG, String.format(
540 "updateLocked: preparing broadcast: action=%s enable=0x%08x disable=0x%08x",
541 action, enableFlags, disableFlags));
542 }
543
Dianne Hackborn7299c412010-03-04 18:41:49 -0800544 // Send the ordered broadcast; the result receiver will receive after all
545 // broadcasts have been sent. If any broadcast receiver changes the result
546 // code from the initial value of RESULT_OK, then the result receiver will
547 // not launch the corresponding dock application. This gives apps a chance
548 // to override the behavior and stay in their app even when the device is
549 // placed into a dock.
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700550 Intent intent = new Intent(action);
551 intent.putExtra("enableFlags", enableFlags);
552 intent.putExtra("disableFlags", disableFlags);
553 mContext.sendOrderedBroadcast(intent, null,
Dianne Hackborn7299c412010-03-04 18:41:49 -0800554 mResultReceiver, null, Activity.RESULT_OK, null, null);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800555 // Attempting to make this transition a little more clean, we are going
556 // to hold off on doing a configuration change until we have finished
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700557 // the broadcast and started the home activity.
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800558 mHoldingConfiguration = true;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700559 } else {
560 Intent homeIntent = null;
561 if (mCarModeEnabled) {
Daniel Sandler11ddf532011-11-16 11:10:03 -0800562 if (ENABLE_LAUNCH_CAR_DOCK_APP
563 && (enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700564 homeIntent = buildHomeIntent(Intent.CATEGORY_CAR_DOCK);
565 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400566 } else if (isDeskDockState(mDockState)) {
Daniel Sandler11ddf532011-11-16 11:10:03 -0800567 if (ENABLE_LAUNCH_DESK_DOCK_APP
568 && (enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700569 homeIntent = buildHomeIntent(Intent.CATEGORY_DESK_DOCK);
570 }
571 } else {
572 if ((disableFlags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
573 homeIntent = buildHomeIntent(Intent.CATEGORY_HOME);
574 }
575 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400576
577 if (LOG) {
578 Slog.v(TAG, "updateLocked: null action, mDockState="
579 + mDockState +", firing homeIntent: " + homeIntent);
580 }
581
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700582 if (homeIntent != null) {
583 try {
584 mContext.startActivity(homeIntent);
585 } catch (ActivityNotFoundException e) {
586 }
587 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800588 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100589
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700590 updateConfigurationLocked(true);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500591
592 // keep screen on when charging and in car mode
593 boolean keepScreenOn = mCharging &&
594 ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
595 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
596 if (keepScreenOn != mWakeLock.isHeld()) {
597 if (keepScreenOn) {
598 mWakeLock.acquire();
599 } else {
600 mWakeLock.release();
601 }
602 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800603 } finally {
604 Binder.restoreCallingIdentity(ident);
605 }
606 }
607
608 private void adjustStatusBarCarModeLocked() {
609 if (mStatusBarManager == null) {
610 mStatusBarManager = (StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
611 }
612
Joe Onorato089de882010-04-12 08:18:45 -0700613 // Fear not: StatusBarManagerService manages a list of requests to disable
Dianne Hackborn7299c412010-03-04 18:41:49 -0800614 // features of the status bar; these are ORed together to form the
615 // active disabled list. So if (for example) the device is locked and
616 // the status bar should be totally disabled, the calls below will
617 // have no effect until the device is unlocked.
618 if (mStatusBarManager != null) {
619 mStatusBarManager.disable(mCarModeEnabled
620 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
621 : StatusBarManager.DISABLE_NONE);
622 }
623
624 if (mNotificationManager == null) {
625 mNotificationManager = (NotificationManager)
626 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
627 }
628
629 if (mNotificationManager != null) {
630 if (mCarModeEnabled) {
631 Intent carModeOffIntent = new Intent(mContext, DisableCarModeActivity.class);
632
633 Notification n = new Notification();
634 n.icon = R.drawable.stat_notify_car_mode;
635 n.defaults = Notification.DEFAULT_LIGHTS;
636 n.flags = Notification.FLAG_ONGOING_EVENT;
637 n.when = 0;
638 n.setLatestEventInfo(
639 mContext,
640 mContext.getString(R.string.car_mode_disable_notification_title),
641 mContext.getString(R.string.car_mode_disable_notification_message),
642 PendingIntent.getActivity(mContext, 0, carModeOffIntent, 0));
643 mNotificationManager.notify(0, n);
644 } else {
645 mNotificationManager.cancel(0);
646 }
647 }
648 }
649
650 private final Handler mHandler = new Handler() {
651
652 boolean mPassiveListenerEnabled;
653 boolean mNetworkListenerEnabled;
Dianne Hackborn57f45032010-06-17 15:49:33 -0700654 boolean mDidFirstInit;
655 long mLastNetworkRegisterTime = -MIN_LOCATION_UPDATE_MS;
656
Dianne Hackborn7299c412010-03-04 18:41:49 -0800657 @Override
658 public void handleMessage(Message msg) {
659 switch (msg.what) {
660 case MSG_UPDATE_TWILIGHT:
661 synchronized (mLock) {
662 if (isDoingNightMode() && mLocation != null
663 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
664 updateTwilightLocked();
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700665 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800666 }
667 }
668 break;
Dianne Hackborn57f45032010-06-17 15:49:33 -0700669 case MSG_GET_NEW_LOCATION_UPDATE:
670 if (!mNetworkListenerEnabled) {
671 // Don't do anything -- we are still trying to get a
672 // location.
673 return;
674 }
675 if ((mLastNetworkRegisterTime+MIN_LOCATION_UPDATE_MS)
676 >= SystemClock.elapsedRealtime()) {
677 // Don't do anything -- it hasn't been long enough
678 // since we last requested an update.
679 return;
680 }
681
682 // Unregister the current location monitor, so we can
683 // register a new one for it to get an immediate update.
684 mNetworkListenerEnabled = false;
685 mLocationManager.removeUpdates(mEmptyLocationListener);
686
687 // Fall through to re-register listener.
Dianne Hackborn7299c412010-03-04 18:41:49 -0800688 case MSG_ENABLE_LOCATION_UPDATES:
689 // enable network provider to receive at least location updates for a given
690 // distance.
691 boolean networkLocationEnabled;
692 try {
693 networkLocationEnabled =
694 mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
695 } catch (Exception e) {
696 // we may get IllegalArgumentException if network location provider
697 // does not exist or is not yet installed.
698 networkLocationEnabled = false;
699 }
700 if (!mNetworkListenerEnabled && networkLocationEnabled) {
701 mNetworkListenerEnabled = true;
Dianne Hackborn57f45032010-06-17 15:49:33 -0700702 mLastNetworkRegisterTime = SystemClock.elapsedRealtime();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800703 mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
704 LOCATION_UPDATE_MS, 0, mEmptyLocationListener);
705
Dianne Hackborn57f45032010-06-17 15:49:33 -0700706 if (!mDidFirstInit) {
707 mDidFirstInit = true;
708 if (mLocation == null) {
709 retrieveLocation();
710 }
711 synchronized (mLock) {
712 if (isDoingNightMode() && mLocation != null
713 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
714 updateTwilightLocked();
715 updateLocked(0, 0);
716 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800717 }
718 }
719 }
720 // enable passive provider to receive updates from location fixes (gps
721 // and network).
722 boolean passiveLocationEnabled;
723 try {
724 passiveLocationEnabled =
725 mLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
726 } catch (Exception e) {
727 // we may get IllegalArgumentException if passive location provider
728 // does not exist or is not yet installed.
729 passiveLocationEnabled = false;
730 }
731 if (!mPassiveListenerEnabled && passiveLocationEnabled) {
732 mPassiveListenerEnabled = true;
733 mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
734 0, LOCATION_UPDATE_DISTANCE_METER , mLocationListener);
735 }
736 if (!(mNetworkListenerEnabled && mPassiveListenerEnabled)) {
737 long interval = msg.getData().getLong(KEY_LAST_UPDATE_INTERVAL);
738 interval *= 1.5;
739 if (interval == 0) {
740 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MIN;
741 } else if (interval > LOCATION_UPDATE_ENABLE_INTERVAL_MAX) {
742 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MAX;
743 }
744 Bundle bundle = new Bundle();
745 bundle.putLong(KEY_LAST_UPDATE_INTERVAL, interval);
746 Message newMsg = mHandler.obtainMessage(MSG_ENABLE_LOCATION_UPDATES);
747 newMsg.setData(bundle);
748 mHandler.sendMessageDelayed(newMsg, interval);
749 }
750 break;
751 }
752 }
753
754 private void retrieveLocation() {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100755 Location location = null;
756 final Iterator<String> providers =
757 mLocationManager.getProviders(new Criteria(), true).iterator();
758 while (providers.hasNext()) {
759 final Location lastKnownLocation =
760 mLocationManager.getLastKnownLocation(providers.next());
761 // pick the most recent location
762 if (location == null || (lastKnownLocation != null &&
763 location.getTime() < lastKnownLocation.getTime())) {
764 location = lastKnownLocation;
765 }
766 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800767 // In the case there is no location available (e.g. GPS fix or network location
768 // is not available yet), the longitude of the location is estimated using the timezone,
769 // latitude and accuracy are set to get a good average.
770 if (location == null) {
771 Time currentTime = new Time();
772 currentTime.set(System.currentTimeMillis());
773 double lngOffset = FACTOR_GMT_OFFSET_LONGITUDE *
774 (currentTime.gmtoff - (currentTime.isDst > 0 ? 3600 : 0));
775 location = new Location("fake");
776 location.setLongitude(lngOffset);
777 location.setLatitude(0);
778 location.setAccuracy(417000.0f);
779 location.setTime(System.currentTimeMillis());
780 }
781 synchronized (mLock) {
782 mLocation = location;
783 }
784 }
785 };
786
787 void updateTwilightLocked() {
788 if (mLocation == null) {
789 return;
790 }
791 final long currentTime = System.currentTimeMillis();
792 boolean nightMode;
793 // calculate current twilight
794 TwilightCalculator tw = new TwilightCalculator();
795 tw.calculateTwilight(currentTime,
796 mLocation.getLatitude(), mLocation.getLongitude());
797 if (tw.mState == TwilightCalculator.DAY) {
798 nightMode = false;
799 } else {
800 nightMode = true;
801 }
802
803 // schedule next update
804 long nextUpdate = 0;
805 if (tw.mSunrise == -1 || tw.mSunset == -1) {
806 // In the case the day or night never ends the update is scheduled 12 hours later.
807 nextUpdate = currentTime + 12 * DateUtils.HOUR_IN_MILLIS;
808 } else {
809 final int mLastTwilightState = tw.mState;
810 // add some extra time to be on the save side.
811 nextUpdate += DateUtils.MINUTE_IN_MILLIS;
812 if (currentTime > tw.mSunset) {
813 // next update should be on the following day
814 tw.calculateTwilight(currentTime
815 + DateUtils.DAY_IN_MILLIS, mLocation.getLatitude(),
816 mLocation.getLongitude());
817 }
818
819 if (mLastTwilightState == TwilightCalculator.NIGHT) {
820 nextUpdate += tw.mSunrise;
821 } else {
822 nextUpdate += tw.mSunset;
823 }
824 }
825
826 Intent updateIntent = new Intent(ACTION_UPDATE_NIGHT_MODE);
827 PendingIntent pendingIntent =
828 PendingIntent.getBroadcast(mContext, 0, updateIntent, 0);
829 mAlarmManager.cancel(pendingIntent);
830 mAlarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdate, pendingIntent);
831
832 mComputedNightMode = nightMode;
833 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100834
Dianne Hackborn7299c412010-03-04 18:41:49 -0800835 @Override
836 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
837 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
838 != PackageManager.PERMISSION_GRANTED) {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100839
Dianne Hackborn7299c412010-03-04 18:41:49 -0800840 pw.println("Permission Denial: can't dump uimode service from from pid="
841 + Binder.getCallingPid()
842 + ", uid=" + Binder.getCallingUid());
843 return;
844 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100845
Dianne Hackborn7299c412010-03-04 18:41:49 -0800846 synchronized (mLock) {
847 pw.println("Current UI Mode Service state:");
848 pw.print(" mDockState="); pw.print(mDockState);
849 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
850 pw.print(" mNightMode="); pw.print(mNightMode);
851 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
852 pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
853 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800854 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
855 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800856 pw.print(" mSystemReady="); pw.println(mSystemReady);
857 if (mLocation != null) {
858 pw.print(" mLocation="); pw.println(mLocation);
859 }
860 }
861 }
862}