blob: 9493161ca5dd728620603b945b2cdd280b6e2d10 [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 Hackborn2ccda4d2010-03-22 21:49:15 -070047import android.provider.Settings;
Dianne Hackborn7299c412010-03-04 18:41:49 -080048import android.text.format.DateUtils;
49import android.text.format.Time;
50import android.util.Slog;
51
52import java.io.FileDescriptor;
53import java.io.PrintWriter;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010054import java.util.Iterator;
Dianne Hackborn7299c412010-03-04 18:41:49 -080055
56import com.android.internal.R;
57import com.android.internal.app.DisableCarModeActivity;
58
59class UiModeManagerService extends IUiModeManager.Stub {
60 private static final String TAG = UiModeManager.class.getSimpleName();
61 private static final boolean LOG = false;
62
63 private static final String KEY_LAST_UPDATE_INTERVAL = "LAST_UPDATE_INTERVAL";
64
65 private static final int MSG_UPDATE_TWILIGHT = 0;
66 private static final int MSG_ENABLE_LOCATION_UPDATES = 1;
67
68 private static final long LOCATION_UPDATE_MS = 30 * DateUtils.MINUTE_IN_MILLIS;
69 private static final float LOCATION_UPDATE_DISTANCE_METER = 1000 * 20;
70 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MIN = 5000;
71 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MAX = 5 * DateUtils.MINUTE_IN_MILLIS;
72 private static final double FACTOR_GMT_OFFSET_LONGITUDE = 1000.0 * 360.0 / DateUtils.DAY_IN_MILLIS;
73
74 private static final String ACTION_UPDATE_NIGHT_MODE = "com.android.server.action.UPDATE_NIGHT_MODE";
75
76 private final Context mContext;
77
78 final Object mLock = new Object();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010079
Dianne Hackborn7299c412010-03-04 18:41:49 -080080 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
81 private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010082
Dianne Hackborn7299c412010-03-04 18:41:49 -080083 private int mNightMode = UiModeManager.MODE_NIGHT_NO;
84 private boolean mCarModeEnabled = false;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050085 private boolean mCharging = false;
86 private final boolean mCarModeKeepsScreenOn;
87 private final boolean mDeskModeKeepsScreenOn;
Dianne Hackborn7299c412010-03-04 18:41:49 -080088
89 private boolean mComputedNightMode;
90 private int mCurUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080091 private int mSetUiMode = 0;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010092
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080093 private boolean mHoldingConfiguration = false;
Dianne Hackborn7299c412010-03-04 18:41:49 -080094 private Configuration mConfiguration = new Configuration();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010095
Dianne Hackborn7299c412010-03-04 18:41:49 -080096 private boolean mSystemReady;
97
98 private NotificationManager mNotificationManager;
99
100 private AlarmManager mAlarmManager;
101
102 private LocationManager mLocationManager;
103 private Location mLocation;
104 private StatusBarManager mStatusBarManager;
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500105 private final PowerManager.WakeLock mWakeLock;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800106
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700107 static Intent buildHomeIntent(String category) {
108 Intent intent = new Intent(Intent.ACTION_MAIN);
109 intent.addCategory(category);
110 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
111 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
112 return intent;
113 }
114
Dianne Hackborn7299c412010-03-04 18:41:49 -0800115 // The broadcast receiver which receives the result of the ordered broadcast sent when
116 // the dock state changes. The original ordered broadcast is sent with an initial result
117 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
118 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
119 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
120 @Override
121 public void onReceive(Context context, Intent intent) {
122 if (getResultCode() != Activity.RESULT_OK) {
123 return;
124 }
125
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700126 final int enableFlags = intent.getIntExtra("enableFlags", 0);
127 final int disableFlags = intent.getIntExtra("disableFlags", 0);
128
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800129 synchronized (mLock) {
130 // Launch a dock activity
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700131 String category = null;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800132 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700133 // Only launch car home when car mode is enabled and the caller
134 // has asked us to switch to it.
135 if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
136 category = Intent.CATEGORY_CAR_DOCK;
137 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800138 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700139 // Only launch car home when desk mode is enabled and the caller
140 // has asked us to switch to it. Currently re-using the car
141 // mode flag since we don't have a formal API for "desk mode".
142 if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
143 category = Intent.CATEGORY_DESK_DOCK;
144 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800145 } else {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700146 // Launch the standard home app if requested.
147 if ((disableFlags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
148 category = Intent.CATEGORY_HOME;
149 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800150 }
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700151
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800152 if (category != null) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700153 // This is the new activity that will serve as home while
154 // we are in care mode.
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700155 Intent homeIntent = buildHomeIntent(category);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700156
157 // Now we are going to be careful about switching the
158 // configuration and starting the activity -- we need to
159 // do this in a specific order under control of the
160 // activity manager, to do it cleanly. So compute the
161 // new config, but don't set it yet, and let the
162 // activity manager take care of both the start and config
163 // change.
164 Configuration newConfig = null;
165 if (mHoldingConfiguration) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700166 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700167 updateConfigurationLocked(false);
168 newConfig = mConfiguration;
169 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800170 try {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700171 ActivityManagerNative.getDefault().startActivityWithConfig(
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700172 null, homeIntent, null, null, 0, null, null, 0, false, false,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700173 newConfig);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700174 mHoldingConfiguration = false;
175 } catch (RemoteException e) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800176 Slog.w(TAG, e.getCause());
177 }
178 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100179
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800180 if (mHoldingConfiguration) {
181 mHoldingConfiguration = false;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700182 updateConfigurationLocked(true);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800183 }
184 }
185 }
186 };
187
188 private final BroadcastReceiver mTwilightUpdateReceiver = new BroadcastReceiver() {
189 @Override
190 public void onReceive(Context context, Intent intent) {
191 if (isDoingNightMode() && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
192 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
193 }
194 }
195 };
196
197 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
198 @Override
199 public void onReceive(Context context, Intent intent) {
200 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
201 Intent.EXTRA_DOCK_STATE_UNDOCKED);
202 updateDockState(state);
203 }
204 };
205
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500206 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
207 @Override
208 public void onReceive(Context context, Intent intent) {
209 mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
210 synchronized (mLock) {
211 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700212 updateLocked(0, 0);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500213 }
214 }
215 }
216 };
217
Dianne Hackborn7299c412010-03-04 18:41:49 -0800218 // A LocationListener to initialize the network location provider. The location updates
219 // are handled through the passive location provider.
220 private final LocationListener mEmptyLocationListener = new LocationListener() {
221 public void onLocationChanged(Location location) {
222 }
223
224 public void onProviderDisabled(String provider) {
225 }
226
227 public void onProviderEnabled(String provider) {
228 }
229
230 public void onStatusChanged(String provider, int status, Bundle extras) {
231 }
232 };
233
234 private final LocationListener mLocationListener = new LocationListener() {
235
236 public void onLocationChanged(Location location) {
237 final boolean hasMoved = hasMoved(location);
238 final boolean hasBetterAccuracy = mLocation == null
239 || location.getAccuracy() < mLocation.getAccuracy();
240 if (hasMoved || hasBetterAccuracy) {
241 synchronized (mLock) {
242 mLocation = location;
243 if (hasMoved && isDoingNightMode()
244 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
245 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
246 }
247 }
248 }
249 }
250
251 public void onProviderDisabled(String provider) {
252 }
253
254 public void onProviderEnabled(String provider) {
255 }
256
257 public void onStatusChanged(String provider, int status, Bundle extras) {
258 }
259
260 /*
261 * The user has moved if the accuracy circles of the two locations
262 * don't overlap.
263 */
264 private boolean hasMoved(Location location) {
265 if (location == null) {
266 return false;
267 }
268 if (mLocation == null) {
269 return true;
270 }
271
272 /* if new location is older than the current one, the devices hasn't
273 * moved.
274 */
275 if (location.getTime() < mLocation.getTime()) {
276 return false;
277 }
278
279 /* Get the distance between the two points */
280 float distance = mLocation.distanceTo(location);
281
282 /* Get the total accuracy radius for both locations */
283 float totalAccuracy = mLocation.getAccuracy() + location.getAccuracy();
284
285 /* If the distance is greater than the combined accuracy of the two
286 * points then they can't overlap and hence the user has moved.
287 */
288 return distance >= totalAccuracy;
289 }
290 };
291
292 public UiModeManagerService(Context context) {
293 mContext = context;
294
295 ServiceManager.addService(Context.UI_MODE_SERVICE, this);
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100296
Dianne Hackborn7299c412010-03-04 18:41:49 -0800297 mAlarmManager =
298 (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
299 mLocationManager =
300 (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
301 mContext.registerReceiver(mTwilightUpdateReceiver,
302 new IntentFilter(ACTION_UPDATE_NIGHT_MODE));
303 mContext.registerReceiver(mDockModeReceiver,
304 new IntentFilter(Intent.ACTION_DOCK_EVENT));
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500305 mContext.registerReceiver(mBatteryReceiver,
306 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
307
308 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
309 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800310
311 mConfiguration.setToDefaults();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500312
313 mCarModeKeepsScreenOn = (context.getResources().getInteger(
314 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
315 mDeskModeKeepsScreenOn = (context.getResources().getInteger(
316 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700317
318 mNightMode = Settings.Secure.getInt(mContext.getContentResolver(),
319 Settings.Secure.UI_NIGHT_MODE, UiModeManager.MODE_NIGHT_AUTO);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800320 }
321
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700322 public void disableCarMode(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800323 synchronized (mLock) {
324 setCarModeLocked(false);
Mike Lockwood924e1642010-03-05 11:56:53 -0500325 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700326 updateLocked(0, flags);
Mike Lockwood924e1642010-03-05 11:56:53 -0500327 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800328 }
329 }
330
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700331 public void enableCarMode(int flags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800332 synchronized (mLock) {
333 setCarModeLocked(true);
Mike Lockwood924e1642010-03-05 11:56:53 -0500334 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700335 updateLocked(flags, 0);
Mike Lockwood924e1642010-03-05 11:56:53 -0500336 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800337 }
338 }
339
340 public int getCurrentModeType() {
341 synchronized (mLock) {
342 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
343 }
344 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100345
Dianne Hackborn7299c412010-03-04 18:41:49 -0800346 public void setNightMode(int mode) throws RemoteException {
347 synchronized (mLock) {
348 switch (mode) {
349 case UiModeManager.MODE_NIGHT_NO:
350 case UiModeManager.MODE_NIGHT_YES:
351 case UiModeManager.MODE_NIGHT_AUTO:
352 break;
353 default:
354 throw new IllegalArgumentException("Unknown mode: " + mode);
355 }
356 if (!isDoingNightMode()) {
357 return;
358 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100359
Dianne Hackborn7299c412010-03-04 18:41:49 -0800360 if (mNightMode != mode) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700361 long ident = Binder.clearCallingIdentity();
362 Settings.Secure.putInt(mContext.getContentResolver(),
363 Settings.Secure.UI_NIGHT_MODE, mode);
364 Binder.restoreCallingIdentity(ident);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800365 mNightMode = mode;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700366 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800367 }
368 }
369 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100370
Dianne Hackborn7299c412010-03-04 18:41:49 -0800371 public int getNightMode() throws RemoteException {
372 return mNightMode;
373 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100374
Dianne Hackborn7299c412010-03-04 18:41:49 -0800375 void systemReady() {
376 synchronized (mLock) {
377 mSystemReady = true;
378 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700379 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800380 mHandler.sendEmptyMessage(MSG_ENABLE_LOCATION_UPDATES);
381 }
382 }
383
384 boolean isDoingNightMode() {
385 return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
386 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100387
Dianne Hackborn7299c412010-03-04 18:41:49 -0800388 void setCarModeLocked(boolean enabled) {
389 if (mCarModeEnabled != enabled) {
390 mCarModeEnabled = enabled;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800391 }
392 }
393
394 void updateDockState(int newState) {
395 synchronized (mLock) {
396 if (newState != mDockState) {
397 mDockState = newState;
Mike Lockwood924e1642010-03-05 11:56:53 -0500398 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800399 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700400 updateLocked(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800401 }
402 }
403 }
404 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500405
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700406 final void updateConfigurationLocked(boolean sendIt) {
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400407 int uiMode = Configuration.UI_MODE_TYPE_NORMAL;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800408 if (mCarModeEnabled) {
409 uiMode = Configuration.UI_MODE_TYPE_CAR;
410 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
411 uiMode = Configuration.UI_MODE_TYPE_DESK;
412 }
Dianne Hackborn9c9c5322010-03-30 23:12:22 -0700413 if (mCarModeEnabled) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800414 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
415 updateTwilightLocked();
416 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
417 : Configuration.UI_MODE_NIGHT_NO;
418 } else {
419 uiMode |= mNightMode << 4;
420 }
421 } else {
422 // Disabling the car mode clears the night mode.
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400423 uiMode = (uiMode & ~Configuration.UI_MODE_NIGHT_MASK) | Configuration.UI_MODE_NIGHT_NO;
424 }
425
426 if (LOG) {
427 Slog.d(TAG,
428 "updateConfigurationLocked: mDockState=" + mDockState
429 + "; mCarMode=" + mCarModeEnabled
430 + "; mNightMode=" + mNightMode
431 + "; uiMode=" + uiMode);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800432 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100433
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800434 mCurUiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100435
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800436 if (!mHoldingConfiguration && uiMode != mSetUiMode) {
437 mSetUiMode = uiMode;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700438 mConfiguration.uiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100439
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700440 if (sendIt) {
441 try {
442 ActivityManagerNative.getDefault().updateConfiguration(mConfiguration);
443 } catch (RemoteException e) {
444 Slog.w(TAG, "Failure communicating with activity manager", e);
445 }
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800446 }
447 }
448 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100449
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700450 final void updateLocked(int enableFlags, int disableFlags) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800451 long ident = Binder.clearCallingIdentity();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100452
Dianne Hackborn7299c412010-03-04 18:41:49 -0800453 try {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800454 String action = null;
455 String oldAction = null;
456 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
Tobias Haamel780b2602010-03-15 12:54:45 +0100457 adjustStatusBarCarModeLocked();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800458 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
459 } else if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_DESK) {
460 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
461 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100462
Dianne Hackborn7299c412010-03-04 18:41:49 -0800463 if (mCarModeEnabled) {
464 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
465 adjustStatusBarCarModeLocked();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100466
Dianne Hackborn7299c412010-03-04 18:41:49 -0800467 if (oldAction != null) {
468 mContext.sendBroadcast(new Intent(oldAction));
469 }
470 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
471 action = UiModeManager.ACTION_ENTER_CAR_MODE;
472 }
473 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
474 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_DESK) {
475 if (oldAction != null) {
476 mContext.sendBroadcast(new Intent(oldAction));
477 }
478 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_DESK;
479 action = UiModeManager.ACTION_ENTER_DESK_MODE;
480 }
481 } else {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800482 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
483 action = oldAction;
484 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100485
Dianne Hackborn7299c412010-03-04 18:41:49 -0800486 if (action != null) {
487 // Send the ordered broadcast; the result receiver will receive after all
488 // broadcasts have been sent. If any broadcast receiver changes the result
489 // code from the initial value of RESULT_OK, then the result receiver will
490 // not launch the corresponding dock application. This gives apps a chance
491 // to override the behavior and stay in their app even when the device is
492 // placed into a dock.
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700493 Intent intent = new Intent(action);
494 intent.putExtra("enableFlags", enableFlags);
495 intent.putExtra("disableFlags", disableFlags);
496 mContext.sendOrderedBroadcast(intent, null,
Dianne Hackborn7299c412010-03-04 18:41:49 -0800497 mResultReceiver, null, Activity.RESULT_OK, null, null);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800498 // Attempting to make this transition a little more clean, we are going
499 // to hold off on doing a configuration change until we have finished
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700500 // the broadcast and started the home activity.
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800501 mHoldingConfiguration = true;
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700502 } else {
503 Intent homeIntent = null;
504 if (mCarModeEnabled) {
505 if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
506 homeIntent = buildHomeIntent(Intent.CATEGORY_CAR_DOCK);
507 }
508 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
509 if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
510 homeIntent = buildHomeIntent(Intent.CATEGORY_DESK_DOCK);
511 }
512 } else {
513 if ((disableFlags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
514 homeIntent = buildHomeIntent(Intent.CATEGORY_HOME);
515 }
516 }
517 if (homeIntent != null) {
518 try {
519 mContext.startActivity(homeIntent);
520 } catch (ActivityNotFoundException e) {
521 }
522 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800523 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100524
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700525 updateConfigurationLocked(true);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500526
527 // keep screen on when charging and in car mode
528 boolean keepScreenOn = mCharging &&
529 ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
530 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
531 if (keepScreenOn != mWakeLock.isHeld()) {
532 if (keepScreenOn) {
533 mWakeLock.acquire();
534 } else {
535 mWakeLock.release();
536 }
537 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800538 } finally {
539 Binder.restoreCallingIdentity(ident);
540 }
541 }
542
543 private void adjustStatusBarCarModeLocked() {
544 if (mStatusBarManager == null) {
545 mStatusBarManager = (StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
546 }
547
Joe Onorato089de882010-04-12 08:18:45 -0700548 // Fear not: StatusBarManagerService manages a list of requests to disable
Dianne Hackborn7299c412010-03-04 18:41:49 -0800549 // features of the status bar; these are ORed together to form the
550 // active disabled list. So if (for example) the device is locked and
551 // the status bar should be totally disabled, the calls below will
552 // have no effect until the device is unlocked.
553 if (mStatusBarManager != null) {
554 mStatusBarManager.disable(mCarModeEnabled
555 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
556 : StatusBarManager.DISABLE_NONE);
557 }
558
559 if (mNotificationManager == null) {
560 mNotificationManager = (NotificationManager)
561 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
562 }
563
564 if (mNotificationManager != null) {
565 if (mCarModeEnabled) {
566 Intent carModeOffIntent = new Intent(mContext, DisableCarModeActivity.class);
567
568 Notification n = new Notification();
569 n.icon = R.drawable.stat_notify_car_mode;
570 n.defaults = Notification.DEFAULT_LIGHTS;
571 n.flags = Notification.FLAG_ONGOING_EVENT;
572 n.when = 0;
573 n.setLatestEventInfo(
574 mContext,
575 mContext.getString(R.string.car_mode_disable_notification_title),
576 mContext.getString(R.string.car_mode_disable_notification_message),
577 PendingIntent.getActivity(mContext, 0, carModeOffIntent, 0));
578 mNotificationManager.notify(0, n);
579 } else {
580 mNotificationManager.cancel(0);
581 }
582 }
583 }
584
585 private final Handler mHandler = new Handler() {
586
587 boolean mPassiveListenerEnabled;
588 boolean mNetworkListenerEnabled;
589
590 @Override
591 public void handleMessage(Message msg) {
592 switch (msg.what) {
593 case MSG_UPDATE_TWILIGHT:
594 synchronized (mLock) {
595 if (isDoingNightMode() && mLocation != null
596 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
597 updateTwilightLocked();
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700598 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800599 }
600 }
601 break;
602 case MSG_ENABLE_LOCATION_UPDATES:
603 // enable network provider to receive at least location updates for a given
604 // distance.
605 boolean networkLocationEnabled;
606 try {
607 networkLocationEnabled =
608 mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
609 } catch (Exception e) {
610 // we may get IllegalArgumentException if network location provider
611 // does not exist or is not yet installed.
612 networkLocationEnabled = false;
613 }
614 if (!mNetworkListenerEnabled && networkLocationEnabled) {
615 mNetworkListenerEnabled = true;
616 mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
617 LOCATION_UPDATE_MS, 0, mEmptyLocationListener);
618
619 if (mLocation == null) {
620 retrieveLocation();
621 }
622 synchronized (mLock) {
623 if (isDoingNightMode() && mLocation != null
624 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
625 updateTwilightLocked();
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700626 updateLocked(0, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800627 }
628 }
629 }
630 // enable passive provider to receive updates from location fixes (gps
631 // and network).
632 boolean passiveLocationEnabled;
633 try {
634 passiveLocationEnabled =
635 mLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
636 } catch (Exception e) {
637 // we may get IllegalArgumentException if passive location provider
638 // does not exist or is not yet installed.
639 passiveLocationEnabled = false;
640 }
641 if (!mPassiveListenerEnabled && passiveLocationEnabled) {
642 mPassiveListenerEnabled = true;
643 mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
644 0, LOCATION_UPDATE_DISTANCE_METER , mLocationListener);
645 }
646 if (!(mNetworkListenerEnabled && mPassiveListenerEnabled)) {
647 long interval = msg.getData().getLong(KEY_LAST_UPDATE_INTERVAL);
648 interval *= 1.5;
649 if (interval == 0) {
650 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MIN;
651 } else if (interval > LOCATION_UPDATE_ENABLE_INTERVAL_MAX) {
652 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MAX;
653 }
654 Bundle bundle = new Bundle();
655 bundle.putLong(KEY_LAST_UPDATE_INTERVAL, interval);
656 Message newMsg = mHandler.obtainMessage(MSG_ENABLE_LOCATION_UPDATES);
657 newMsg.setData(bundle);
658 mHandler.sendMessageDelayed(newMsg, interval);
659 }
660 break;
661 }
662 }
663
664 private void retrieveLocation() {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100665 Location location = null;
666 final Iterator<String> providers =
667 mLocationManager.getProviders(new Criteria(), true).iterator();
668 while (providers.hasNext()) {
669 final Location lastKnownLocation =
670 mLocationManager.getLastKnownLocation(providers.next());
671 // pick the most recent location
672 if (location == null || (lastKnownLocation != null &&
673 location.getTime() < lastKnownLocation.getTime())) {
674 location = lastKnownLocation;
675 }
676 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800677 // In the case there is no location available (e.g. GPS fix or network location
678 // is not available yet), the longitude of the location is estimated using the timezone,
679 // latitude and accuracy are set to get a good average.
680 if (location == null) {
681 Time currentTime = new Time();
682 currentTime.set(System.currentTimeMillis());
683 double lngOffset = FACTOR_GMT_OFFSET_LONGITUDE *
684 (currentTime.gmtoff - (currentTime.isDst > 0 ? 3600 : 0));
685 location = new Location("fake");
686 location.setLongitude(lngOffset);
687 location.setLatitude(0);
688 location.setAccuracy(417000.0f);
689 location.setTime(System.currentTimeMillis());
690 }
691 synchronized (mLock) {
692 mLocation = location;
693 }
694 }
695 };
696
697 void updateTwilightLocked() {
698 if (mLocation == null) {
699 return;
700 }
701 final long currentTime = System.currentTimeMillis();
702 boolean nightMode;
703 // calculate current twilight
704 TwilightCalculator tw = new TwilightCalculator();
705 tw.calculateTwilight(currentTime,
706 mLocation.getLatitude(), mLocation.getLongitude());
707 if (tw.mState == TwilightCalculator.DAY) {
708 nightMode = false;
709 } else {
710 nightMode = true;
711 }
712
713 // schedule next update
714 long nextUpdate = 0;
715 if (tw.mSunrise == -1 || tw.mSunset == -1) {
716 // In the case the day or night never ends the update is scheduled 12 hours later.
717 nextUpdate = currentTime + 12 * DateUtils.HOUR_IN_MILLIS;
718 } else {
719 final int mLastTwilightState = tw.mState;
720 // add some extra time to be on the save side.
721 nextUpdate += DateUtils.MINUTE_IN_MILLIS;
722 if (currentTime > tw.mSunset) {
723 // next update should be on the following day
724 tw.calculateTwilight(currentTime
725 + DateUtils.DAY_IN_MILLIS, mLocation.getLatitude(),
726 mLocation.getLongitude());
727 }
728
729 if (mLastTwilightState == TwilightCalculator.NIGHT) {
730 nextUpdate += tw.mSunrise;
731 } else {
732 nextUpdate += tw.mSunset;
733 }
734 }
735
736 Intent updateIntent = new Intent(ACTION_UPDATE_NIGHT_MODE);
737 PendingIntent pendingIntent =
738 PendingIntent.getBroadcast(mContext, 0, updateIntent, 0);
739 mAlarmManager.cancel(pendingIntent);
740 mAlarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdate, pendingIntent);
741
742 mComputedNightMode = nightMode;
743 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100744
Dianne Hackborn7299c412010-03-04 18:41:49 -0800745 @Override
746 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
747 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
748 != PackageManager.PERMISSION_GRANTED) {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100749
Dianne Hackborn7299c412010-03-04 18:41:49 -0800750 pw.println("Permission Denial: can't dump uimode service from from pid="
751 + Binder.getCallingPid()
752 + ", uid=" + Binder.getCallingUid());
753 return;
754 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100755
Dianne Hackborn7299c412010-03-04 18:41:49 -0800756 synchronized (mLock) {
757 pw.println("Current UI Mode Service state:");
758 pw.print(" mDockState="); pw.print(mDockState);
759 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
760 pw.print(" mNightMode="); pw.print(mNightMode);
761 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
762 pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
763 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800764 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
765 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800766 pw.print(" mSystemReady="); pw.println(mSystemReady);
767 if (mLocation != null) {
768 pw.print(" mLocation="); pw.println(mLocation);
769 }
770 }
771 }
772}