blob: 1850b9a5cca1b549dd0ad717a65809f49c41c2b6 [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 Hackborn7299c412010-03-04 18:41:49 -080028import android.content.BroadcastReceiver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
33import android.content.res.Configuration;
34import android.location.Criteria;
35import android.location.Location;
36import android.location.LocationListener;
37import android.location.LocationManager;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050038import android.os.BatteryManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080039import android.os.Binder;
40import android.os.Bundle;
41import android.os.Handler;
42import android.os.Message;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050043import android.os.PowerManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080044import android.os.RemoteException;
45import android.os.ServiceManager;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -070046import android.provider.Settings;
Dianne Hackborn7299c412010-03-04 18:41:49 -080047import android.text.format.DateUtils;
48import android.text.format.Time;
49import android.util.Slog;
50
51import java.io.FileDescriptor;
52import java.io.PrintWriter;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010053import java.util.Iterator;
Dianne Hackborn7299c412010-03-04 18:41:49 -080054
55import com.android.internal.R;
56import com.android.internal.app.DisableCarModeActivity;
57
58class UiModeManagerService extends IUiModeManager.Stub {
59 private static final String TAG = UiModeManager.class.getSimpleName();
60 private static final boolean LOG = false;
61
62 private static final String KEY_LAST_UPDATE_INTERVAL = "LAST_UPDATE_INTERVAL";
63
64 private static final int MSG_UPDATE_TWILIGHT = 0;
65 private static final int MSG_ENABLE_LOCATION_UPDATES = 1;
66
67 private static final long LOCATION_UPDATE_MS = 30 * DateUtils.MINUTE_IN_MILLIS;
68 private static final float LOCATION_UPDATE_DISTANCE_METER = 1000 * 20;
69 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MIN = 5000;
70 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MAX = 5 * DateUtils.MINUTE_IN_MILLIS;
71 private static final double FACTOR_GMT_OFFSET_LONGITUDE = 1000.0 * 360.0 / DateUtils.DAY_IN_MILLIS;
72
73 private static final String ACTION_UPDATE_NIGHT_MODE = "com.android.server.action.UPDATE_NIGHT_MODE";
74
75 private final Context mContext;
76
77 final Object mLock = new Object();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010078
Dianne Hackborn7299c412010-03-04 18:41:49 -080079 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
80 private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010081
Dianne Hackborn7299c412010-03-04 18:41:49 -080082 private int mNightMode = UiModeManager.MODE_NIGHT_NO;
83 private boolean mCarModeEnabled = false;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050084 private boolean mCharging = false;
85 private final boolean mCarModeKeepsScreenOn;
86 private final boolean mDeskModeKeepsScreenOn;
Dianne Hackborn7299c412010-03-04 18:41:49 -080087
88 private boolean mComputedNightMode;
89 private int mCurUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080090 private int mSetUiMode = 0;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010091
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080092 private boolean mHoldingConfiguration = false;
Dianne Hackborn7299c412010-03-04 18:41:49 -080093 private Configuration mConfiguration = new Configuration();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010094
Dianne Hackborn7299c412010-03-04 18:41:49 -080095 private boolean mSystemReady;
96
97 private NotificationManager mNotificationManager;
98
99 private AlarmManager mAlarmManager;
100
101 private LocationManager mLocationManager;
102 private Location mLocation;
103 private StatusBarManager mStatusBarManager;
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500104 private final PowerManager.WakeLock mWakeLock;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800105
106 // The broadcast receiver which receives the result of the ordered broadcast sent when
107 // the dock state changes. The original ordered broadcast is sent with an initial result
108 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
109 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
110 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
111 @Override
112 public void onReceive(Context context, Intent intent) {
113 if (getResultCode() != Activity.RESULT_OK) {
114 return;
115 }
116
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800117 synchronized (mLock) {
118 // Launch a dock activity
119 String category;
120 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
121 // Only launch car home when car mode is enabled.
122 category = Intent.CATEGORY_CAR_DOCK;
123 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
124 category = Intent.CATEGORY_DESK_DOCK;
125 } else {
126 category = null;
127 }
128 if (category != null) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700129 // This is the new activity that will serve as home while
130 // we are in care mode.
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800131 intent = new Intent(Intent.ACTION_MAIN);
132 intent.addCategory(category);
133 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
134 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700135
136 // Now we are going to be careful about switching the
137 // configuration and starting the activity -- we need to
138 // do this in a specific order under control of the
139 // activity manager, to do it cleanly. So compute the
140 // new config, but don't set it yet, and let the
141 // activity manager take care of both the start and config
142 // change.
143 Configuration newConfig = null;
144 if (mHoldingConfiguration) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700145 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700146 updateConfigurationLocked(false);
147 newConfig = mConfiguration;
148 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800149 try {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700150 ActivityManagerNative.getDefault().startActivityWithConfig(
151 null, intent, null, null, 0, null, null, 0, false, false,
152 newConfig);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700153 mHoldingConfiguration = false;
154 } catch (RemoteException e) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800155 Slog.w(TAG, e.getCause());
156 }
157 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100158
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800159 if (mHoldingConfiguration) {
160 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700161 updateConfigurationLocked(true);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800162 }
163 }
164 }
165 };
166
167 private final BroadcastReceiver mTwilightUpdateReceiver = new BroadcastReceiver() {
168 @Override
169 public void onReceive(Context context, Intent intent) {
170 if (isDoingNightMode() && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
171 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
172 }
173 }
174 };
175
176 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
177 @Override
178 public void onReceive(Context context, Intent intent) {
179 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
180 Intent.EXTRA_DOCK_STATE_UNDOCKED);
181 updateDockState(state);
182 }
183 };
184
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500185 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
186 @Override
187 public void onReceive(Context context, Intent intent) {
188 mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
189 synchronized (mLock) {
190 if (mSystemReady) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700191 updateLocked(0);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500192 }
193 }
194 }
195 };
196
Dianne Hackborn7299c412010-03-04 18:41:49 -0800197 // A LocationListener to initialize the network location provider. The location updates
198 // are handled through the passive location provider.
199 private final LocationListener mEmptyLocationListener = new LocationListener() {
200 public void onLocationChanged(Location location) {
201 }
202
203 public void onProviderDisabled(String provider) {
204 }
205
206 public void onProviderEnabled(String provider) {
207 }
208
209 public void onStatusChanged(String provider, int status, Bundle extras) {
210 }
211 };
212
213 private final LocationListener mLocationListener = new LocationListener() {
214
215 public void onLocationChanged(Location location) {
216 final boolean hasMoved = hasMoved(location);
217 final boolean hasBetterAccuracy = mLocation == null
218 || location.getAccuracy() < mLocation.getAccuracy();
219 if (hasMoved || hasBetterAccuracy) {
220 synchronized (mLock) {
221 mLocation = location;
222 if (hasMoved && isDoingNightMode()
223 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
224 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
225 }
226 }
227 }
228 }
229
230 public void onProviderDisabled(String provider) {
231 }
232
233 public void onProviderEnabled(String provider) {
234 }
235
236 public void onStatusChanged(String provider, int status, Bundle extras) {
237 }
238
239 /*
240 * The user has moved if the accuracy circles of the two locations
241 * don't overlap.
242 */
243 private boolean hasMoved(Location location) {
244 if (location == null) {
245 return false;
246 }
247 if (mLocation == null) {
248 return true;
249 }
250
251 /* if new location is older than the current one, the devices hasn't
252 * moved.
253 */
254 if (location.getTime() < mLocation.getTime()) {
255 return false;
256 }
257
258 /* Get the distance between the two points */
259 float distance = mLocation.distanceTo(location);
260
261 /* Get the total accuracy radius for both locations */
262 float totalAccuracy = mLocation.getAccuracy() + location.getAccuracy();
263
264 /* If the distance is greater than the combined accuracy of the two
265 * points then they can't overlap and hence the user has moved.
266 */
267 return distance >= totalAccuracy;
268 }
269 };
270
271 public UiModeManagerService(Context context) {
272 mContext = context;
273
274 ServiceManager.addService(Context.UI_MODE_SERVICE, this);
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100275
Dianne Hackborn7299c412010-03-04 18:41:49 -0800276 mAlarmManager =
277 (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
278 mLocationManager =
279 (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
280 mContext.registerReceiver(mTwilightUpdateReceiver,
281 new IntentFilter(ACTION_UPDATE_NIGHT_MODE));
282 mContext.registerReceiver(mDockModeReceiver,
283 new IntentFilter(Intent.ACTION_DOCK_EVENT));
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500284 mContext.registerReceiver(mBatteryReceiver,
285 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
286
287 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
288 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800289
290 mConfiguration.setToDefaults();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500291
292 mCarModeKeepsScreenOn = (context.getResources().getInteger(
293 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
294 mDeskModeKeepsScreenOn = (context.getResources().getInteger(
295 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700296
297 mNightMode = Settings.Secure.getInt(mContext.getContentResolver(),
298 Settings.Secure.UI_NIGHT_MODE, UiModeManager.MODE_NIGHT_AUTO);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800299 }
300
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700301 public void disableCarMode(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800302 synchronized (mLock) {
303 setCarModeLocked(false);
Mike Lockwood924e1642010-03-05 11:56:53 -0500304 if (mSystemReady) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700305 updateLocked(flags);
Mike Lockwood924e1642010-03-05 11:56:53 -0500306 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800307 }
308 }
309
310 public void enableCarMode() {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800311 synchronized (mLock) {
312 setCarModeLocked(true);
Mike Lockwood924e1642010-03-05 11:56:53 -0500313 if (mSystemReady) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700314 updateLocked(0);
Mike Lockwood924e1642010-03-05 11:56:53 -0500315 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800316 }
317 }
318
319 public int getCurrentModeType() {
320 synchronized (mLock) {
321 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
322 }
323 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100324
Dianne Hackborn7299c412010-03-04 18:41:49 -0800325 public void setNightMode(int mode) throws RemoteException {
326 synchronized (mLock) {
327 switch (mode) {
328 case UiModeManager.MODE_NIGHT_NO:
329 case UiModeManager.MODE_NIGHT_YES:
330 case UiModeManager.MODE_NIGHT_AUTO:
331 break;
332 default:
333 throw new IllegalArgumentException("Unknown mode: " + mode);
334 }
335 if (!isDoingNightMode()) {
336 return;
337 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100338
Dianne Hackborn7299c412010-03-04 18:41:49 -0800339 if (mNightMode != mode) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700340 long ident = Binder.clearCallingIdentity();
341 Settings.Secure.putInt(mContext.getContentResolver(),
342 Settings.Secure.UI_NIGHT_MODE, mode);
343 Binder.restoreCallingIdentity(ident);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800344 mNightMode = mode;
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700345 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800346 }
347 }
348 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100349
Dianne Hackborn7299c412010-03-04 18:41:49 -0800350 public int getNightMode() throws RemoteException {
351 return mNightMode;
352 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100353
Dianne Hackborn7299c412010-03-04 18:41:49 -0800354 void systemReady() {
355 synchronized (mLock) {
356 mSystemReady = true;
357 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700358 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800359 mHandler.sendEmptyMessage(MSG_ENABLE_LOCATION_UPDATES);
360 }
361 }
362
363 boolean isDoingNightMode() {
364 return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
365 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100366
Dianne Hackborn7299c412010-03-04 18:41:49 -0800367 void setCarModeLocked(boolean enabled) {
368 if (mCarModeEnabled != enabled) {
369 mCarModeEnabled = enabled;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800370 }
371 }
372
373 void updateDockState(int newState) {
374 synchronized (mLock) {
375 if (newState != mDockState) {
376 mDockState = newState;
Mike Lockwood924e1642010-03-05 11:56:53 -0500377 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800378 if (mSystemReady) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700379 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800380 }
381 }
382 }
383 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500384
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700385 final void updateConfigurationLocked(boolean sendIt) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800386 int uiMode = 0;
387 if (mCarModeEnabled) {
388 uiMode = Configuration.UI_MODE_TYPE_CAR;
389 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
390 uiMode = Configuration.UI_MODE_TYPE_DESK;
391 }
Dianne Hackborn9c9c5322010-03-30 23:12:22 -0700392 if (mCarModeEnabled) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800393 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
394 updateTwilightLocked();
395 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
396 : Configuration.UI_MODE_NIGHT_NO;
397 } else {
398 uiMode |= mNightMode << 4;
399 }
400 } else {
401 // Disabling the car mode clears the night mode.
402 uiMode = Configuration.UI_MODE_TYPE_NORMAL |
403 Configuration.UI_MODE_NIGHT_NO;
404 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100405
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800406 mCurUiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100407
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800408 if (!mHoldingConfiguration && uiMode != mSetUiMode) {
409 mSetUiMode = uiMode;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700410 mConfiguration.uiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100411
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700412 if (sendIt) {
413 try {
414 ActivityManagerNative.getDefault().updateConfiguration(mConfiguration);
415 } catch (RemoteException e) {
416 Slog.w(TAG, "Failure communicating with activity manager", e);
417 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800418 }
419 }
420 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100421
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700422 final void updateLocked(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800423 long ident = Binder.clearCallingIdentity();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100424
Dianne Hackborn7299c412010-03-04 18:41:49 -0800425 try {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800426 String action = null;
427 String oldAction = null;
428 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
Tobias Haamel780b2602010-03-15 12:54:45 +0100429 adjustStatusBarCarModeLocked();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800430 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
431 } else if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_DESK) {
432 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
433 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100434
Dianne Hackborn7299c412010-03-04 18:41:49 -0800435 if (mCarModeEnabled) {
436 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
437 adjustStatusBarCarModeLocked();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100438
Dianne Hackborn7299c412010-03-04 18:41:49 -0800439 if (oldAction != null) {
440 mContext.sendBroadcast(new Intent(oldAction));
441 }
442 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
443 action = UiModeManager.ACTION_ENTER_CAR_MODE;
444 }
445 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
446 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_DESK) {
447 if (oldAction != null) {
448 mContext.sendBroadcast(new Intent(oldAction));
449 }
450 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_DESK;
451 action = UiModeManager.ACTION_ENTER_DESK_MODE;
452 }
453 } else {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800454 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
455 action = oldAction;
456 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100457
Dianne Hackborn7299c412010-03-04 18:41:49 -0800458 if (action != null) {
459 // Send the ordered broadcast; the result receiver will receive after all
460 // broadcasts have been sent. If any broadcast receiver changes the result
461 // code from the initial value of RESULT_OK, then the result receiver will
462 // not launch the corresponding dock application. This gives apps a chance
463 // to override the behavior and stay in their app even when the device is
464 // placed into a dock.
465 mContext.sendOrderedBroadcast(new Intent(action), null,
466 mResultReceiver, null, Activity.RESULT_OK, null, null);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800467 // Attempting to make this transition a little more clean, we are going
468 // to hold off on doing a configuration change until we have finished
469 // the broacast and started the home activity.
470 mHoldingConfiguration = true;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800471 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100472
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700473 if (oldAction != null && (flags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
474 // We are exiting the special mode, and have been asked to return
475 // to the main home screen while doing so. To keep this clean, we
476 // have the activity manager switch the configuration for us at the
477 // same time as the switch.
478 try {
479 Intent intent = new Intent(Intent.ACTION_MAIN);
480 intent.addCategory(Intent.CATEGORY_HOME);
481 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborne2522462010-03-29 18:41:30 -0700482 mHoldingConfiguration = false;
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700483 updateConfigurationLocked(false);
484 ActivityManagerNative.getDefault().startActivityWithConfig(
485 null, intent, null, null, 0, null, null, 0, false, false,
486 mConfiguration);
487 } catch (RemoteException e) {
488 Slog.w(TAG, e.getCause());
489 }
490 } else {
491 updateConfigurationLocked(true);
492 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500493
494 // keep screen on when charging and in car mode
495 boolean keepScreenOn = mCharging &&
496 ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
497 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
498 if (keepScreenOn != mWakeLock.isHeld()) {
499 if (keepScreenOn) {
500 mWakeLock.acquire();
501 } else {
502 mWakeLock.release();
503 }
504 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800505 } finally {
506 Binder.restoreCallingIdentity(ident);
507 }
508 }
509
510 private void adjustStatusBarCarModeLocked() {
511 if (mStatusBarManager == null) {
512 mStatusBarManager = (StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
513 }
514
515 // Fear not: StatusBarService manages a list of requests to disable
516 // features of the status bar; these are ORed together to form the
517 // active disabled list. So if (for example) the device is locked and
518 // the status bar should be totally disabled, the calls below will
519 // have no effect until the device is unlocked.
520 if (mStatusBarManager != null) {
521 mStatusBarManager.disable(mCarModeEnabled
522 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
523 : StatusBarManager.DISABLE_NONE);
524 }
525
526 if (mNotificationManager == null) {
527 mNotificationManager = (NotificationManager)
528 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
529 }
530
531 if (mNotificationManager != null) {
532 if (mCarModeEnabled) {
533 Intent carModeOffIntent = new Intent(mContext, DisableCarModeActivity.class);
534
535 Notification n = new Notification();
536 n.icon = R.drawable.stat_notify_car_mode;
537 n.defaults = Notification.DEFAULT_LIGHTS;
538 n.flags = Notification.FLAG_ONGOING_EVENT;
539 n.when = 0;
540 n.setLatestEventInfo(
541 mContext,
542 mContext.getString(R.string.car_mode_disable_notification_title),
543 mContext.getString(R.string.car_mode_disable_notification_message),
544 PendingIntent.getActivity(mContext, 0, carModeOffIntent, 0));
545 mNotificationManager.notify(0, n);
546 } else {
547 mNotificationManager.cancel(0);
548 }
549 }
550 }
551
552 private final Handler mHandler = new Handler() {
553
554 boolean mPassiveListenerEnabled;
555 boolean mNetworkListenerEnabled;
556
557 @Override
558 public void handleMessage(Message msg) {
559 switch (msg.what) {
560 case MSG_UPDATE_TWILIGHT:
561 synchronized (mLock) {
562 if (isDoingNightMode() && mLocation != null
563 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
564 updateTwilightLocked();
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700565 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800566 }
567 }
568 break;
569 case MSG_ENABLE_LOCATION_UPDATES:
570 // enable network provider to receive at least location updates for a given
571 // distance.
572 boolean networkLocationEnabled;
573 try {
574 networkLocationEnabled =
575 mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
576 } catch (Exception e) {
577 // we may get IllegalArgumentException if network location provider
578 // does not exist or is not yet installed.
579 networkLocationEnabled = false;
580 }
581 if (!mNetworkListenerEnabled && networkLocationEnabled) {
582 mNetworkListenerEnabled = true;
583 mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
584 LOCATION_UPDATE_MS, 0, mEmptyLocationListener);
585
586 if (mLocation == null) {
587 retrieveLocation();
588 }
589 synchronized (mLock) {
590 if (isDoingNightMode() && mLocation != null
591 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
592 updateTwilightLocked();
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700593 updateLocked(0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800594 }
595 }
596 }
597 // enable passive provider to receive updates from location fixes (gps
598 // and network).
599 boolean passiveLocationEnabled;
600 try {
601 passiveLocationEnabled =
602 mLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
603 } catch (Exception e) {
604 // we may get IllegalArgumentException if passive location provider
605 // does not exist or is not yet installed.
606 passiveLocationEnabled = false;
607 }
608 if (!mPassiveListenerEnabled && passiveLocationEnabled) {
609 mPassiveListenerEnabled = true;
610 mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
611 0, LOCATION_UPDATE_DISTANCE_METER , mLocationListener);
612 }
613 if (!(mNetworkListenerEnabled && mPassiveListenerEnabled)) {
614 long interval = msg.getData().getLong(KEY_LAST_UPDATE_INTERVAL);
615 interval *= 1.5;
616 if (interval == 0) {
617 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MIN;
618 } else if (interval > LOCATION_UPDATE_ENABLE_INTERVAL_MAX) {
619 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MAX;
620 }
621 Bundle bundle = new Bundle();
622 bundle.putLong(KEY_LAST_UPDATE_INTERVAL, interval);
623 Message newMsg = mHandler.obtainMessage(MSG_ENABLE_LOCATION_UPDATES);
624 newMsg.setData(bundle);
625 mHandler.sendMessageDelayed(newMsg, interval);
626 }
627 break;
628 }
629 }
630
631 private void retrieveLocation() {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100632 Location location = null;
633 final Iterator<String> providers =
634 mLocationManager.getProviders(new Criteria(), true).iterator();
635 while (providers.hasNext()) {
636 final Location lastKnownLocation =
637 mLocationManager.getLastKnownLocation(providers.next());
638 // pick the most recent location
639 if (location == null || (lastKnownLocation != null &&
640 location.getTime() < lastKnownLocation.getTime())) {
641 location = lastKnownLocation;
642 }
643 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800644 // In the case there is no location available (e.g. GPS fix or network location
645 // is not available yet), the longitude of the location is estimated using the timezone,
646 // latitude and accuracy are set to get a good average.
647 if (location == null) {
648 Time currentTime = new Time();
649 currentTime.set(System.currentTimeMillis());
650 double lngOffset = FACTOR_GMT_OFFSET_LONGITUDE *
651 (currentTime.gmtoff - (currentTime.isDst > 0 ? 3600 : 0));
652 location = new Location("fake");
653 location.setLongitude(lngOffset);
654 location.setLatitude(0);
655 location.setAccuracy(417000.0f);
656 location.setTime(System.currentTimeMillis());
657 }
658 synchronized (mLock) {
659 mLocation = location;
660 }
661 }
662 };
663
664 void updateTwilightLocked() {
665 if (mLocation == null) {
666 return;
667 }
668 final long currentTime = System.currentTimeMillis();
669 boolean nightMode;
670 // calculate current twilight
671 TwilightCalculator tw = new TwilightCalculator();
672 tw.calculateTwilight(currentTime,
673 mLocation.getLatitude(), mLocation.getLongitude());
674 if (tw.mState == TwilightCalculator.DAY) {
675 nightMode = false;
676 } else {
677 nightMode = true;
678 }
679
680 // schedule next update
681 long nextUpdate = 0;
682 if (tw.mSunrise == -1 || tw.mSunset == -1) {
683 // In the case the day or night never ends the update is scheduled 12 hours later.
684 nextUpdate = currentTime + 12 * DateUtils.HOUR_IN_MILLIS;
685 } else {
686 final int mLastTwilightState = tw.mState;
687 // add some extra time to be on the save side.
688 nextUpdate += DateUtils.MINUTE_IN_MILLIS;
689 if (currentTime > tw.mSunset) {
690 // next update should be on the following day
691 tw.calculateTwilight(currentTime
692 + DateUtils.DAY_IN_MILLIS, mLocation.getLatitude(),
693 mLocation.getLongitude());
694 }
695
696 if (mLastTwilightState == TwilightCalculator.NIGHT) {
697 nextUpdate += tw.mSunrise;
698 } else {
699 nextUpdate += tw.mSunset;
700 }
701 }
702
703 Intent updateIntent = new Intent(ACTION_UPDATE_NIGHT_MODE);
704 PendingIntent pendingIntent =
705 PendingIntent.getBroadcast(mContext, 0, updateIntent, 0);
706 mAlarmManager.cancel(pendingIntent);
707 mAlarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdate, pendingIntent);
708
709 mComputedNightMode = nightMode;
710 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100711
Dianne Hackborn7299c412010-03-04 18:41:49 -0800712 @Override
713 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
714 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
715 != PackageManager.PERMISSION_GRANTED) {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100716
Dianne Hackborn7299c412010-03-04 18:41:49 -0800717 pw.println("Permission Denial: can't dump uimode service from from pid="
718 + Binder.getCallingPid()
719 + ", uid=" + Binder.getCallingUid());
720 return;
721 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100722
Dianne Hackborn7299c412010-03-04 18:41:49 -0800723 synchronized (mLock) {
724 pw.println("Current UI Mode Service state:");
725 pw.print(" mDockState="); pw.print(mDockState);
726 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
727 pw.print(" mNightMode="); pw.print(mNightMode);
728 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
729 pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
730 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800731 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
732 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800733 pw.print(" mSystemReady="); pw.println(mSystemReady);
734 if (mLocation != null) {
735 pw.print(" mLocation="); pw.println(mLocation);
736 }
737 }
738 }
739}