blob: c40650a49e562d74946c843013550bdc9cc642b2 [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;
22import android.app.IActivityManager;
23import android.app.IUiModeManager;
24import android.app.Notification;
25import android.app.NotificationManager;
26import android.app.PendingIntent;
27import android.app.StatusBarManager;
28import android.app.UiModeManager;
29import android.content.ActivityNotFoundException;
30import android.content.BroadcastReceiver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
35import android.content.res.Configuration;
36import android.location.Criteria;
37import android.location.Location;
38import android.location.LocationListener;
39import android.location.LocationManager;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050040import android.os.BatteryManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080041import android.os.Binder;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.Message;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050045import android.os.PowerManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080046import android.os.RemoteException;
47import android.os.ServiceManager;
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;
68
69 private static final long LOCATION_UPDATE_MS = 30 * DateUtils.MINUTE_IN_MILLIS;
70 private static final float LOCATION_UPDATE_DISTANCE_METER = 1000 * 20;
71 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MIN = 5000;
72 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MAX = 5 * DateUtils.MINUTE_IN_MILLIS;
73 private static final double FACTOR_GMT_OFFSET_LONGITUDE = 1000.0 * 360.0 / DateUtils.DAY_IN_MILLIS;
74
75 private static final String ACTION_UPDATE_NIGHT_MODE = "com.android.server.action.UPDATE_NIGHT_MODE";
76
77 private final Context mContext;
78
79 final Object mLock = new Object();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010080
Dianne Hackborn7299c412010-03-04 18:41:49 -080081 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
82 private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010083
Dianne Hackborn7299c412010-03-04 18:41:49 -080084 private int mNightMode = UiModeManager.MODE_NIGHT_NO;
85 private boolean mCarModeEnabled = false;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050086 private boolean mCharging = false;
87 private final boolean mCarModeKeepsScreenOn;
88 private final boolean mDeskModeKeepsScreenOn;
Dianne Hackborn7299c412010-03-04 18:41:49 -080089
90 private boolean mComputedNightMode;
91 private int mCurUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080092 private int mSetUiMode = 0;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010093
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080094 private boolean mHoldingConfiguration = false;
Dianne Hackborn7299c412010-03-04 18:41:49 -080095 private Configuration mConfiguration = new Configuration();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010096
Dianne Hackborn7299c412010-03-04 18:41:49 -080097 private boolean mSystemReady;
98
99 private NotificationManager mNotificationManager;
100
101 private AlarmManager mAlarmManager;
102
103 private LocationManager mLocationManager;
104 private Location mLocation;
105 private StatusBarManager mStatusBarManager;
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500106 private final PowerManager.WakeLock mWakeLock;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800107
108 // The broadcast receiver which receives the result of the ordered broadcast sent when
109 // the dock state changes. The original ordered broadcast is sent with an initial result
110 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
111 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
112 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
113 @Override
114 public void onReceive(Context context, Intent intent) {
115 if (getResultCode() != Activity.RESULT_OK) {
116 return;
117 }
118
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800119 synchronized (mLock) {
120 // Launch a dock activity
121 String category;
122 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
123 // Only launch car home when car mode is enabled.
124 category = Intent.CATEGORY_CAR_DOCK;
125 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
126 category = Intent.CATEGORY_DESK_DOCK;
127 } else {
128 category = null;
129 }
130 if (category != null) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700131 // This is the new activity that will serve as home while
132 // we are in care mode.
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800133 intent = new Intent(Intent.ACTION_MAIN);
134 intent.addCategory(category);
135 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
136 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700137
138 // Now we are going to be careful about switching the
139 // configuration and starting the activity -- we need to
140 // do this in a specific order under control of the
141 // activity manager, to do it cleanly. So compute the
142 // new config, but don't set it yet, and let the
143 // activity manager take care of both the start and config
144 // change.
145 Configuration newConfig = null;
146 if (mHoldingConfiguration) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700147 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700148 updateConfigurationLocked(false);
149 newConfig = mConfiguration;
150 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800151 try {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700152 ActivityManagerNative.getDefault().startActivityWithConfig(
153 null, intent, null, null, 0, null, null, 0, false, false,
154 newConfig);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700155 mHoldingConfiguration = false;
156 } catch (RemoteException e) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800157 Slog.w(TAG, e.getCause());
158 }
159 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100160
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800161 if (mHoldingConfiguration) {
162 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700163 updateConfigurationLocked(true);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800164 }
165 }
166 }
167 };
168
169 private final BroadcastReceiver mTwilightUpdateReceiver = new BroadcastReceiver() {
170 @Override
171 public void onReceive(Context context, Intent intent) {
172 if (isDoingNightMode() && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
173 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
174 }
175 }
176 };
177
178 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
179 @Override
180 public void onReceive(Context context, Intent intent) {
181 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
182 Intent.EXTRA_DOCK_STATE_UNDOCKED);
183 updateDockState(state);
184 }
185 };
186
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500187 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
188 @Override
189 public void onReceive(Context context, Intent intent) {
190 mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
191 synchronized (mLock) {
192 if (mSystemReady) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700193 updateLocked(0);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500194 }
195 }
196 }
197 };
198
Dianne Hackborn7299c412010-03-04 18:41:49 -0800199 // A LocationListener to initialize the network location provider. The location updates
200 // are handled through the passive location provider.
201 private final LocationListener mEmptyLocationListener = new LocationListener() {
202 public void onLocationChanged(Location location) {
203 }
204
205 public void onProviderDisabled(String provider) {
206 }
207
208 public void onProviderEnabled(String provider) {
209 }
210
211 public void onStatusChanged(String provider, int status, Bundle extras) {
212 }
213 };
214
215 private final LocationListener mLocationListener = new LocationListener() {
216
217 public void onLocationChanged(Location location) {
218 final boolean hasMoved = hasMoved(location);
219 final boolean hasBetterAccuracy = mLocation == null
220 || location.getAccuracy() < mLocation.getAccuracy();
221 if (hasMoved || hasBetterAccuracy) {
222 synchronized (mLock) {
223 mLocation = location;
224 if (hasMoved && isDoingNightMode()
225 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
226 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
227 }
228 }
229 }
230 }
231
232 public void onProviderDisabled(String provider) {
233 }
234
235 public void onProviderEnabled(String provider) {
236 }
237
238 public void onStatusChanged(String provider, int status, Bundle extras) {
239 }
240
241 /*
242 * The user has moved if the accuracy circles of the two locations
243 * don't overlap.
244 */
245 private boolean hasMoved(Location location) {
246 if (location == null) {
247 return false;
248 }
249 if (mLocation == null) {
250 return true;
251 }
252
253 /* if new location is older than the current one, the devices hasn't
254 * moved.
255 */
256 if (location.getTime() < mLocation.getTime()) {
257 return false;
258 }
259
260 /* Get the distance between the two points */
261 float distance = mLocation.distanceTo(location);
262
263 /* Get the total accuracy radius for both locations */
264 float totalAccuracy = mLocation.getAccuracy() + location.getAccuracy();
265
266 /* If the distance is greater than the combined accuracy of the two
267 * points then they can't overlap and hence the user has moved.
268 */
269 return distance >= totalAccuracy;
270 }
271 };
272
273 public UiModeManagerService(Context context) {
274 mContext = context;
275
276 ServiceManager.addService(Context.UI_MODE_SERVICE, this);
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100277
Dianne Hackborn7299c412010-03-04 18:41:49 -0800278 mAlarmManager =
279 (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
280 mLocationManager =
281 (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
282 mContext.registerReceiver(mTwilightUpdateReceiver,
283 new IntentFilter(ACTION_UPDATE_NIGHT_MODE));
284 mContext.registerReceiver(mDockModeReceiver,
285 new IntentFilter(Intent.ACTION_DOCK_EVENT));
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500286 mContext.registerReceiver(mBatteryReceiver,
287 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
288
289 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
290 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800291
292 mConfiguration.setToDefaults();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500293
294 mCarModeKeepsScreenOn = (context.getResources().getInteger(
295 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
296 mDeskModeKeepsScreenOn = (context.getResources().getInteger(
297 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700298
299 mNightMode = Settings.Secure.getInt(mContext.getContentResolver(),
300 Settings.Secure.UI_NIGHT_MODE, UiModeManager.MODE_NIGHT_AUTO);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800301 }
302
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700303 public void disableCarMode(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800304 synchronized (mLock) {
305 setCarModeLocked(false);
Mike Lockwood924e1642010-03-05 11:56:53 -0500306 if (mSystemReady) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700307 updateLocked(flags);
Mike Lockwood924e1642010-03-05 11:56:53 -0500308 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800309 }
310 }
311
312 public void enableCarMode() {
313 mContext.enforceCallingOrSelfPermission(
314 android.Manifest.permission.ENABLE_CAR_MODE,
315 "Need ENABLE_CAR_MODE permission");
316 synchronized (mLock) {
317 setCarModeLocked(true);
Mike Lockwood924e1642010-03-05 11:56:53 -0500318 if (mSystemReady) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700319 updateLocked(0);
Mike Lockwood924e1642010-03-05 11:56:53 -0500320 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800321 }
322 }
323
324 public int getCurrentModeType() {
325 synchronized (mLock) {
326 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
327 }
328 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100329
Dianne Hackborn7299c412010-03-04 18:41:49 -0800330 public void setNightMode(int mode) throws RemoteException {
331 synchronized (mLock) {
332 switch (mode) {
333 case UiModeManager.MODE_NIGHT_NO:
334 case UiModeManager.MODE_NIGHT_YES:
335 case UiModeManager.MODE_NIGHT_AUTO:
336 break;
337 default:
338 throw new IllegalArgumentException("Unknown mode: " + mode);
339 }
340 if (!isDoingNightMode()) {
341 return;
342 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100343
Dianne Hackborn7299c412010-03-04 18:41:49 -0800344 if (mNightMode != mode) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700345 long ident = Binder.clearCallingIdentity();
346 Settings.Secure.putInt(mContext.getContentResolver(),
347 Settings.Secure.UI_NIGHT_MODE, mode);
348 Binder.restoreCallingIdentity(ident);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800349 mNightMode = mode;
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700350 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800351 }
352 }
353 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100354
Dianne Hackborn7299c412010-03-04 18:41:49 -0800355 public int getNightMode() throws RemoteException {
356 return mNightMode;
357 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100358
Dianne Hackborn7299c412010-03-04 18:41:49 -0800359 void systemReady() {
360 synchronized (mLock) {
361 mSystemReady = true;
362 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700363 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800364 mHandler.sendEmptyMessage(MSG_ENABLE_LOCATION_UPDATES);
365 }
366 }
367
368 boolean isDoingNightMode() {
369 return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
370 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100371
Dianne Hackborn7299c412010-03-04 18:41:49 -0800372 void setCarModeLocked(boolean enabled) {
373 if (mCarModeEnabled != enabled) {
374 mCarModeEnabled = enabled;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800375 }
376 }
377
378 void updateDockState(int newState) {
379 synchronized (mLock) {
380 if (newState != mDockState) {
381 mDockState = newState;
Mike Lockwood924e1642010-03-05 11:56:53 -0500382 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800383 if (mSystemReady) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700384 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800385 }
386 }
387 }
388 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500389
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700390 final void updateConfigurationLocked(boolean sendIt) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800391 int uiMode = 0;
392 if (mCarModeEnabled) {
393 uiMode = Configuration.UI_MODE_TYPE_CAR;
394 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
395 uiMode = Configuration.UI_MODE_TYPE_DESK;
396 }
397 if (uiMode != 0) {
398 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
399 updateTwilightLocked();
400 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
401 : Configuration.UI_MODE_NIGHT_NO;
402 } else {
403 uiMode |= mNightMode << 4;
404 }
405 } else {
406 // Disabling the car mode clears the night mode.
407 uiMode = Configuration.UI_MODE_TYPE_NORMAL |
408 Configuration.UI_MODE_NIGHT_NO;
409 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100410
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800411 mCurUiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100412
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800413 if (!mHoldingConfiguration && uiMode != mSetUiMode) {
414 mSetUiMode = uiMode;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700415 mConfiguration.uiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100416
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700417 if (sendIt) {
418 try {
419 ActivityManagerNative.getDefault().updateConfiguration(mConfiguration);
420 } catch (RemoteException e) {
421 Slog.w(TAG, "Failure communicating with activity manager", e);
422 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800423 }
424 }
425 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100426
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700427 final void updateLocked(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800428 long ident = Binder.clearCallingIdentity();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100429
Dianne Hackborn7299c412010-03-04 18:41:49 -0800430 try {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800431 String action = null;
432 String oldAction = null;
433 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
Tobias Haamel780b2602010-03-15 12:54:45 +0100434 adjustStatusBarCarModeLocked();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800435 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
436 } else if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_DESK) {
437 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
438 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100439
Dianne Hackborn7299c412010-03-04 18:41:49 -0800440 if (mCarModeEnabled) {
441 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
442 adjustStatusBarCarModeLocked();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100443
Dianne Hackborn7299c412010-03-04 18:41:49 -0800444 if (oldAction != null) {
445 mContext.sendBroadcast(new Intent(oldAction));
446 }
447 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
448 action = UiModeManager.ACTION_ENTER_CAR_MODE;
449 }
450 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
451 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_DESK) {
452 if (oldAction != null) {
453 mContext.sendBroadcast(new Intent(oldAction));
454 }
455 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_DESK;
456 action = UiModeManager.ACTION_ENTER_DESK_MODE;
457 }
458 } else {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800459 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
460 action = oldAction;
461 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100462
Dianne Hackborn7299c412010-03-04 18:41:49 -0800463 if (action != null) {
464 // Send the ordered broadcast; the result receiver will receive after all
465 // broadcasts have been sent. If any broadcast receiver changes the result
466 // code from the initial value of RESULT_OK, then the result receiver will
467 // not launch the corresponding dock application. This gives apps a chance
468 // to override the behavior and stay in their app even when the device is
469 // placed into a dock.
470 mContext.sendOrderedBroadcast(new Intent(action), null,
471 mResultReceiver, null, Activity.RESULT_OK, null, null);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800472 // Attempting to make this transition a little more clean, we are going
473 // to hold off on doing a configuration change until we have finished
474 // the broacast and started the home activity.
475 mHoldingConfiguration = true;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800476 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100477
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700478 if (oldAction != null && (flags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
479 // We are exiting the special mode, and have been asked to return
480 // to the main home screen while doing so. To keep this clean, we
481 // have the activity manager switch the configuration for us at the
482 // same time as the switch.
483 try {
484 Intent intent = new Intent(Intent.ACTION_MAIN);
485 intent.addCategory(Intent.CATEGORY_HOME);
486 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborne2522462010-03-29 18:41:30 -0700487 mHoldingConfiguration = false;
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700488 updateConfigurationLocked(false);
489 ActivityManagerNative.getDefault().startActivityWithConfig(
490 null, intent, null, null, 0, null, null, 0, false, false,
491 mConfiguration);
492 } catch (RemoteException e) {
493 Slog.w(TAG, e.getCause());
494 }
495 } else {
496 updateConfigurationLocked(true);
497 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500498
499 // keep screen on when charging and in car mode
500 boolean keepScreenOn = mCharging &&
501 ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
502 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
503 if (keepScreenOn != mWakeLock.isHeld()) {
504 if (keepScreenOn) {
505 mWakeLock.acquire();
506 } else {
507 mWakeLock.release();
508 }
509 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800510 } finally {
511 Binder.restoreCallingIdentity(ident);
512 }
513 }
514
515 private void adjustStatusBarCarModeLocked() {
516 if (mStatusBarManager == null) {
517 mStatusBarManager = (StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
518 }
519
520 // Fear not: StatusBarService manages a list of requests to disable
521 // features of the status bar; these are ORed together to form the
522 // active disabled list. So if (for example) the device is locked and
523 // the status bar should be totally disabled, the calls below will
524 // have no effect until the device is unlocked.
525 if (mStatusBarManager != null) {
526 mStatusBarManager.disable(mCarModeEnabled
527 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
528 : StatusBarManager.DISABLE_NONE);
529 }
530
531 if (mNotificationManager == null) {
532 mNotificationManager = (NotificationManager)
533 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
534 }
535
536 if (mNotificationManager != null) {
537 if (mCarModeEnabled) {
538 Intent carModeOffIntent = new Intent(mContext, DisableCarModeActivity.class);
539
540 Notification n = new Notification();
541 n.icon = R.drawable.stat_notify_car_mode;
542 n.defaults = Notification.DEFAULT_LIGHTS;
543 n.flags = Notification.FLAG_ONGOING_EVENT;
544 n.when = 0;
545 n.setLatestEventInfo(
546 mContext,
547 mContext.getString(R.string.car_mode_disable_notification_title),
548 mContext.getString(R.string.car_mode_disable_notification_message),
549 PendingIntent.getActivity(mContext, 0, carModeOffIntent, 0));
550 mNotificationManager.notify(0, n);
551 } else {
552 mNotificationManager.cancel(0);
553 }
554 }
555 }
556
557 private final Handler mHandler = new Handler() {
558
559 boolean mPassiveListenerEnabled;
560 boolean mNetworkListenerEnabled;
561
562 @Override
563 public void handleMessage(Message msg) {
564 switch (msg.what) {
565 case MSG_UPDATE_TWILIGHT:
566 synchronized (mLock) {
567 if (isDoingNightMode() && mLocation != null
568 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
569 updateTwilightLocked();
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700570 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800571 }
572 }
573 break;
574 case MSG_ENABLE_LOCATION_UPDATES:
575 // enable network provider to receive at least location updates for a given
576 // distance.
577 boolean networkLocationEnabled;
578 try {
579 networkLocationEnabled =
580 mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
581 } catch (Exception e) {
582 // we may get IllegalArgumentException if network location provider
583 // does not exist or is not yet installed.
584 networkLocationEnabled = false;
585 }
586 if (!mNetworkListenerEnabled && networkLocationEnabled) {
587 mNetworkListenerEnabled = true;
588 mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
589 LOCATION_UPDATE_MS, 0, mEmptyLocationListener);
590
591 if (mLocation == null) {
592 retrieveLocation();
593 }
594 synchronized (mLock) {
595 if (isDoingNightMode() && mLocation != null
596 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
597 updateTwilightLocked();
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700598 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800599 }
600 }
601 }
602 // enable passive provider to receive updates from location fixes (gps
603 // and network).
604 boolean passiveLocationEnabled;
605 try {
606 passiveLocationEnabled =
607 mLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
608 } catch (Exception e) {
609 // we may get IllegalArgumentException if passive location provider
610 // does not exist or is not yet installed.
611 passiveLocationEnabled = false;
612 }
613 if (!mPassiveListenerEnabled && passiveLocationEnabled) {
614 mPassiveListenerEnabled = true;
615 mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
616 0, LOCATION_UPDATE_DISTANCE_METER , mLocationListener);
617 }
618 if (!(mNetworkListenerEnabled && mPassiveListenerEnabled)) {
619 long interval = msg.getData().getLong(KEY_LAST_UPDATE_INTERVAL);
620 interval *= 1.5;
621 if (interval == 0) {
622 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MIN;
623 } else if (interval > LOCATION_UPDATE_ENABLE_INTERVAL_MAX) {
624 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MAX;
625 }
626 Bundle bundle = new Bundle();
627 bundle.putLong(KEY_LAST_UPDATE_INTERVAL, interval);
628 Message newMsg = mHandler.obtainMessage(MSG_ENABLE_LOCATION_UPDATES);
629 newMsg.setData(bundle);
630 mHandler.sendMessageDelayed(newMsg, interval);
631 }
632 break;
633 }
634 }
635
636 private void retrieveLocation() {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100637 Location location = null;
638 final Iterator<String> providers =
639 mLocationManager.getProviders(new Criteria(), true).iterator();
640 while (providers.hasNext()) {
641 final Location lastKnownLocation =
642 mLocationManager.getLastKnownLocation(providers.next());
643 // pick the most recent location
644 if (location == null || (lastKnownLocation != null &&
645 location.getTime() < lastKnownLocation.getTime())) {
646 location = lastKnownLocation;
647 }
648 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800649 // In the case there is no location available (e.g. GPS fix or network location
650 // is not available yet), the longitude of the location is estimated using the timezone,
651 // latitude and accuracy are set to get a good average.
652 if (location == null) {
653 Time currentTime = new Time();
654 currentTime.set(System.currentTimeMillis());
655 double lngOffset = FACTOR_GMT_OFFSET_LONGITUDE *
656 (currentTime.gmtoff - (currentTime.isDst > 0 ? 3600 : 0));
657 location = new Location("fake");
658 location.setLongitude(lngOffset);
659 location.setLatitude(0);
660 location.setAccuracy(417000.0f);
661 location.setTime(System.currentTimeMillis());
662 }
663 synchronized (mLock) {
664 mLocation = location;
665 }
666 }
667 };
668
669 void updateTwilightLocked() {
670 if (mLocation == null) {
671 return;
672 }
673 final long currentTime = System.currentTimeMillis();
674 boolean nightMode;
675 // calculate current twilight
676 TwilightCalculator tw = new TwilightCalculator();
677 tw.calculateTwilight(currentTime,
678 mLocation.getLatitude(), mLocation.getLongitude());
679 if (tw.mState == TwilightCalculator.DAY) {
680 nightMode = false;
681 } else {
682 nightMode = true;
683 }
684
685 // schedule next update
686 long nextUpdate = 0;
687 if (tw.mSunrise == -1 || tw.mSunset == -1) {
688 // In the case the day or night never ends the update is scheduled 12 hours later.
689 nextUpdate = currentTime + 12 * DateUtils.HOUR_IN_MILLIS;
690 } else {
691 final int mLastTwilightState = tw.mState;
692 // add some extra time to be on the save side.
693 nextUpdate += DateUtils.MINUTE_IN_MILLIS;
694 if (currentTime > tw.mSunset) {
695 // next update should be on the following day
696 tw.calculateTwilight(currentTime
697 + DateUtils.DAY_IN_MILLIS, mLocation.getLatitude(),
698 mLocation.getLongitude());
699 }
700
701 if (mLastTwilightState == TwilightCalculator.NIGHT) {
702 nextUpdate += tw.mSunrise;
703 } else {
704 nextUpdate += tw.mSunset;
705 }
706 }
707
708 Intent updateIntent = new Intent(ACTION_UPDATE_NIGHT_MODE);
709 PendingIntent pendingIntent =
710 PendingIntent.getBroadcast(mContext, 0, updateIntent, 0);
711 mAlarmManager.cancel(pendingIntent);
712 mAlarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdate, pendingIntent);
713
714 mComputedNightMode = nightMode;
715 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100716
Dianne Hackborn7299c412010-03-04 18:41:49 -0800717 @Override
718 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
719 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
720 != PackageManager.PERMISSION_GRANTED) {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100721
Dianne Hackborn7299c412010-03-04 18:41:49 -0800722 pw.println("Permission Denial: can't dump uimode service from from pid="
723 + Binder.getCallingPid()
724 + ", uid=" + Binder.getCallingUid());
725 return;
726 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100727
Dianne Hackborn7299c412010-03-04 18:41:49 -0800728 synchronized (mLock) {
729 pw.println("Current UI Mode Service state:");
730 pw.print(" mDockState="); pw.print(mDockState);
731 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
732 pw.print(" mNightMode="); pw.print(mNightMode);
733 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
734 pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
735 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800736 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
737 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800738 pw.print(" mSystemReady="); pw.println(mSystemReady);
739 if (mLocation != null) {
740 pw.print(" mLocation="); pw.println(mLocation);
741 }
742 }
743 }
744}