blob: 5bd23f429ba63296af17206119f311d5d7d534e4 [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;
48import 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
107 // The broadcast receiver which receives the result of the ordered broadcast sent when
108 // the dock state changes. The original ordered broadcast is sent with an initial result
109 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
110 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
111 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
112 @Override
113 public void onReceive(Context context, Intent intent) {
114 if (getResultCode() != Activity.RESULT_OK) {
115 return;
116 }
117
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800118 synchronized (mLock) {
119 // Launch a dock activity
120 String category;
121 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
122 // Only launch car home when car mode is enabled.
123 category = Intent.CATEGORY_CAR_DOCK;
124 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
125 category = Intent.CATEGORY_DESK_DOCK;
126 } else {
127 category = null;
128 }
129 if (category != null) {
130 intent = new Intent(Intent.ACTION_MAIN);
131 intent.addCategory(category);
132 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
133 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
134 try {
135 mContext.startActivity(intent);
136 } catch (ActivityNotFoundException e) {
137 Slog.w(TAG, e.getCause());
138 }
139 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100140
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800141 if (mHoldingConfiguration) {
142 mHoldingConfiguration = false;
143 updateConfigurationLocked();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800144 }
145 }
146 }
147 };
148
149 private final BroadcastReceiver mTwilightUpdateReceiver = new BroadcastReceiver() {
150 @Override
151 public void onReceive(Context context, Intent intent) {
152 if (isDoingNightMode() && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
153 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
154 }
155 }
156 };
157
158 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
159 @Override
160 public void onReceive(Context context, Intent intent) {
161 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
162 Intent.EXTRA_DOCK_STATE_UNDOCKED);
163 updateDockState(state);
164 }
165 };
166
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500167 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
168 @Override
169 public void onReceive(Context context, Intent intent) {
170 mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
171 synchronized (mLock) {
172 if (mSystemReady) {
173 updateLocked();
174 }
175 }
176 }
177 };
178
Dianne Hackborn7299c412010-03-04 18:41:49 -0800179 // A LocationListener to initialize the network location provider. The location updates
180 // are handled through the passive location provider.
181 private final LocationListener mEmptyLocationListener = new LocationListener() {
182 public void onLocationChanged(Location location) {
183 }
184
185 public void onProviderDisabled(String provider) {
186 }
187
188 public void onProviderEnabled(String provider) {
189 }
190
191 public void onStatusChanged(String provider, int status, Bundle extras) {
192 }
193 };
194
195 private final LocationListener mLocationListener = new LocationListener() {
196
197 public void onLocationChanged(Location location) {
198 final boolean hasMoved = hasMoved(location);
199 final boolean hasBetterAccuracy = mLocation == null
200 || location.getAccuracy() < mLocation.getAccuracy();
201 if (hasMoved || hasBetterAccuracy) {
202 synchronized (mLock) {
203 mLocation = location;
204 if (hasMoved && isDoingNightMode()
205 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
206 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
207 }
208 }
209 }
210 }
211
212 public void onProviderDisabled(String provider) {
213 }
214
215 public void onProviderEnabled(String provider) {
216 }
217
218 public void onStatusChanged(String provider, int status, Bundle extras) {
219 }
220
221 /*
222 * The user has moved if the accuracy circles of the two locations
223 * don't overlap.
224 */
225 private boolean hasMoved(Location location) {
226 if (location == null) {
227 return false;
228 }
229 if (mLocation == null) {
230 return true;
231 }
232
233 /* if new location is older than the current one, the devices hasn't
234 * moved.
235 */
236 if (location.getTime() < mLocation.getTime()) {
237 return false;
238 }
239
240 /* Get the distance between the two points */
241 float distance = mLocation.distanceTo(location);
242
243 /* Get the total accuracy radius for both locations */
244 float totalAccuracy = mLocation.getAccuracy() + location.getAccuracy();
245
246 /* If the distance is greater than the combined accuracy of the two
247 * points then they can't overlap and hence the user has moved.
248 */
249 return distance >= totalAccuracy;
250 }
251 };
252
253 public UiModeManagerService(Context context) {
254 mContext = context;
255
256 ServiceManager.addService(Context.UI_MODE_SERVICE, this);
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100257
Dianne Hackborn7299c412010-03-04 18:41:49 -0800258 mAlarmManager =
259 (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
260 mLocationManager =
261 (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
262 mContext.registerReceiver(mTwilightUpdateReceiver,
263 new IntentFilter(ACTION_UPDATE_NIGHT_MODE));
264 mContext.registerReceiver(mDockModeReceiver,
265 new IntentFilter(Intent.ACTION_DOCK_EVENT));
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500266 mContext.registerReceiver(mBatteryReceiver,
267 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
268
269 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
270 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800271
272 mConfiguration.setToDefaults();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500273
274 mCarModeKeepsScreenOn = (context.getResources().getInteger(
275 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
276 mDeskModeKeepsScreenOn = (context.getResources().getInteger(
277 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800278 }
279
280 public void disableCarMode() {
281 synchronized (mLock) {
282 setCarModeLocked(false);
Mike Lockwood924e1642010-03-05 11:56:53 -0500283 if (mSystemReady) {
284 updateLocked();
285 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800286 }
287 }
288
289 public void enableCarMode() {
290 mContext.enforceCallingOrSelfPermission(
291 android.Manifest.permission.ENABLE_CAR_MODE,
292 "Need ENABLE_CAR_MODE permission");
293 synchronized (mLock) {
294 setCarModeLocked(true);
Mike Lockwood924e1642010-03-05 11:56:53 -0500295 if (mSystemReady) {
296 updateLocked();
297 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800298 }
299 }
300
301 public int getCurrentModeType() {
302 synchronized (mLock) {
303 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
304 }
305 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100306
Dianne Hackborn7299c412010-03-04 18:41:49 -0800307 public void setNightMode(int mode) throws RemoteException {
308 synchronized (mLock) {
309 switch (mode) {
310 case UiModeManager.MODE_NIGHT_NO:
311 case UiModeManager.MODE_NIGHT_YES:
312 case UiModeManager.MODE_NIGHT_AUTO:
313 break;
314 default:
315 throw new IllegalArgumentException("Unknown mode: " + mode);
316 }
317 if (!isDoingNightMode()) {
318 return;
319 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100320
Dianne Hackborn7299c412010-03-04 18:41:49 -0800321 if (mNightMode != mode) {
322 mNightMode = mode;
323 updateLocked();
324 }
325 }
326 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100327
Dianne Hackborn7299c412010-03-04 18:41:49 -0800328 public int getNightMode() throws RemoteException {
329 return mNightMode;
330 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100331
Dianne Hackborn7299c412010-03-04 18:41:49 -0800332 void systemReady() {
333 synchronized (mLock) {
334 mSystemReady = true;
335 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
336 updateLocked();
337 mHandler.sendEmptyMessage(MSG_ENABLE_LOCATION_UPDATES);
338 }
339 }
340
341 boolean isDoingNightMode() {
342 return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
343 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100344
Dianne Hackborn7299c412010-03-04 18:41:49 -0800345 void setCarModeLocked(boolean enabled) {
346 if (mCarModeEnabled != enabled) {
347 mCarModeEnabled = enabled;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800348 }
349 }
350
351 void updateDockState(int newState) {
352 synchronized (mLock) {
353 if (newState != mDockState) {
354 mDockState = newState;
Mike Lockwood924e1642010-03-05 11:56:53 -0500355 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800356 if (mSystemReady) {
357 updateLocked();
358 }
359 }
360 }
361 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500362
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800363 final void updateConfigurationLocked() {
364 int uiMode = 0;
365 if (mCarModeEnabled) {
366 uiMode = Configuration.UI_MODE_TYPE_CAR;
367 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
368 uiMode = Configuration.UI_MODE_TYPE_DESK;
369 }
370 if (uiMode != 0) {
371 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
372 updateTwilightLocked();
373 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
374 : Configuration.UI_MODE_NIGHT_NO;
375 } else {
376 uiMode |= mNightMode << 4;
377 }
378 } else {
379 // Disabling the car mode clears the night mode.
380 uiMode = Configuration.UI_MODE_TYPE_NORMAL |
381 Configuration.UI_MODE_NIGHT_NO;
382 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100383
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800384 mCurUiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100385
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800386 if (!mHoldingConfiguration && uiMode != mSetUiMode) {
387 mSetUiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100388
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800389 try {
390 final IActivityManager am = ActivityManagerNative.getDefault();
391 mConfiguration.uiMode = uiMode;
392 am.updateConfiguration(mConfiguration);
393 } catch (RemoteException e) {
394 Slog.w(TAG, "Failure communicating with activity manager", e);
395 }
396 }
397 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100398
Dianne Hackborn7299c412010-03-04 18:41:49 -0800399 final void updateLocked() {
400 long ident = Binder.clearCallingIdentity();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100401
Dianne Hackborn7299c412010-03-04 18:41:49 -0800402 try {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800403 String action = null;
404 String oldAction = null;
405 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
Tobias Haamel780b2602010-03-15 12:54:45 +0100406 adjustStatusBarCarModeLocked();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800407 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
408 } else if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_DESK) {
409 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
410 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100411
Dianne Hackborn7299c412010-03-04 18:41:49 -0800412 if (mCarModeEnabled) {
413 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
414 adjustStatusBarCarModeLocked();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100415
Dianne Hackborn7299c412010-03-04 18:41:49 -0800416 if (oldAction != null) {
417 mContext.sendBroadcast(new Intent(oldAction));
418 }
419 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
420 action = UiModeManager.ACTION_ENTER_CAR_MODE;
421 }
422 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
423 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_DESK) {
424 if (oldAction != null) {
425 mContext.sendBroadcast(new Intent(oldAction));
426 }
427 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_DESK;
428 action = UiModeManager.ACTION_ENTER_DESK_MODE;
429 }
430 } else {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800431 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
432 action = oldAction;
433 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100434
Dianne Hackborn7299c412010-03-04 18:41:49 -0800435 if (action != null) {
436 // Send the ordered broadcast; the result receiver will receive after all
437 // broadcasts have been sent. If any broadcast receiver changes the result
438 // code from the initial value of RESULT_OK, then the result receiver will
439 // not launch the corresponding dock application. This gives apps a chance
440 // to override the behavior and stay in their app even when the device is
441 // placed into a dock.
442 mContext.sendOrderedBroadcast(new Intent(action), null,
443 mResultReceiver, null, Activity.RESULT_OK, null, null);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800444 // Attempting to make this transition a little more clean, we are going
445 // to hold off on doing a configuration change until we have finished
446 // the broacast and started the home activity.
447 mHoldingConfiguration = true;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800448 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100449
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800450 updateConfigurationLocked();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500451
452 // keep screen on when charging and in car mode
453 boolean keepScreenOn = mCharging &&
454 ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
455 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
456 if (keepScreenOn != mWakeLock.isHeld()) {
457 if (keepScreenOn) {
458 mWakeLock.acquire();
459 } else {
460 mWakeLock.release();
461 }
462 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800463 } finally {
464 Binder.restoreCallingIdentity(ident);
465 }
466 }
467
468 private void adjustStatusBarCarModeLocked() {
469 if (mStatusBarManager == null) {
470 mStatusBarManager = (StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
471 }
472
473 // Fear not: StatusBarService manages a list of requests to disable
474 // features of the status bar; these are ORed together to form the
475 // active disabled list. So if (for example) the device is locked and
476 // the status bar should be totally disabled, the calls below will
477 // have no effect until the device is unlocked.
478 if (mStatusBarManager != null) {
479 mStatusBarManager.disable(mCarModeEnabled
480 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
481 : StatusBarManager.DISABLE_NONE);
482 }
483
484 if (mNotificationManager == null) {
485 mNotificationManager = (NotificationManager)
486 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
487 }
488
489 if (mNotificationManager != null) {
490 if (mCarModeEnabled) {
491 Intent carModeOffIntent = new Intent(mContext, DisableCarModeActivity.class);
492
493 Notification n = new Notification();
494 n.icon = R.drawable.stat_notify_car_mode;
495 n.defaults = Notification.DEFAULT_LIGHTS;
496 n.flags = Notification.FLAG_ONGOING_EVENT;
497 n.when = 0;
498 n.setLatestEventInfo(
499 mContext,
500 mContext.getString(R.string.car_mode_disable_notification_title),
501 mContext.getString(R.string.car_mode_disable_notification_message),
502 PendingIntent.getActivity(mContext, 0, carModeOffIntent, 0));
503 mNotificationManager.notify(0, n);
504 } else {
505 mNotificationManager.cancel(0);
506 }
507 }
508 }
509
510 private final Handler mHandler = new Handler() {
511
512 boolean mPassiveListenerEnabled;
513 boolean mNetworkListenerEnabled;
514
515 @Override
516 public void handleMessage(Message msg) {
517 switch (msg.what) {
518 case MSG_UPDATE_TWILIGHT:
519 synchronized (mLock) {
520 if (isDoingNightMode() && mLocation != null
521 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
522 updateTwilightLocked();
523 updateLocked();
524 }
525 }
526 break;
527 case MSG_ENABLE_LOCATION_UPDATES:
528 // enable network provider to receive at least location updates for a given
529 // distance.
530 boolean networkLocationEnabled;
531 try {
532 networkLocationEnabled =
533 mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
534 } catch (Exception e) {
535 // we may get IllegalArgumentException if network location provider
536 // does not exist or is not yet installed.
537 networkLocationEnabled = false;
538 }
539 if (!mNetworkListenerEnabled && networkLocationEnabled) {
540 mNetworkListenerEnabled = true;
541 mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
542 LOCATION_UPDATE_MS, 0, mEmptyLocationListener);
543
544 if (mLocation == null) {
545 retrieveLocation();
546 }
547 synchronized (mLock) {
548 if (isDoingNightMode() && mLocation != null
549 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
550 updateTwilightLocked();
551 updateLocked();
552 }
553 }
554 }
555 // enable passive provider to receive updates from location fixes (gps
556 // and network).
557 boolean passiveLocationEnabled;
558 try {
559 passiveLocationEnabled =
560 mLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
561 } catch (Exception e) {
562 // we may get IllegalArgumentException if passive location provider
563 // does not exist or is not yet installed.
564 passiveLocationEnabled = false;
565 }
566 if (!mPassiveListenerEnabled && passiveLocationEnabled) {
567 mPassiveListenerEnabled = true;
568 mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
569 0, LOCATION_UPDATE_DISTANCE_METER , mLocationListener);
570 }
571 if (!(mNetworkListenerEnabled && mPassiveListenerEnabled)) {
572 long interval = msg.getData().getLong(KEY_LAST_UPDATE_INTERVAL);
573 interval *= 1.5;
574 if (interval == 0) {
575 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MIN;
576 } else if (interval > LOCATION_UPDATE_ENABLE_INTERVAL_MAX) {
577 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MAX;
578 }
579 Bundle bundle = new Bundle();
580 bundle.putLong(KEY_LAST_UPDATE_INTERVAL, interval);
581 Message newMsg = mHandler.obtainMessage(MSG_ENABLE_LOCATION_UPDATES);
582 newMsg.setData(bundle);
583 mHandler.sendMessageDelayed(newMsg, interval);
584 }
585 break;
586 }
587 }
588
589 private void retrieveLocation() {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100590 Location location = null;
591 final Iterator<String> providers =
592 mLocationManager.getProviders(new Criteria(), true).iterator();
593 while (providers.hasNext()) {
594 final Location lastKnownLocation =
595 mLocationManager.getLastKnownLocation(providers.next());
596 // pick the most recent location
597 if (location == null || (lastKnownLocation != null &&
598 location.getTime() < lastKnownLocation.getTime())) {
599 location = lastKnownLocation;
600 }
601 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800602 // In the case there is no location available (e.g. GPS fix or network location
603 // is not available yet), the longitude of the location is estimated using the timezone,
604 // latitude and accuracy are set to get a good average.
605 if (location == null) {
606 Time currentTime = new Time();
607 currentTime.set(System.currentTimeMillis());
608 double lngOffset = FACTOR_GMT_OFFSET_LONGITUDE *
609 (currentTime.gmtoff - (currentTime.isDst > 0 ? 3600 : 0));
610 location = new Location("fake");
611 location.setLongitude(lngOffset);
612 location.setLatitude(0);
613 location.setAccuracy(417000.0f);
614 location.setTime(System.currentTimeMillis());
615 }
616 synchronized (mLock) {
617 mLocation = location;
618 }
619 }
620 };
621
622 void updateTwilightLocked() {
623 if (mLocation == null) {
624 return;
625 }
626 final long currentTime = System.currentTimeMillis();
627 boolean nightMode;
628 // calculate current twilight
629 TwilightCalculator tw = new TwilightCalculator();
630 tw.calculateTwilight(currentTime,
631 mLocation.getLatitude(), mLocation.getLongitude());
632 if (tw.mState == TwilightCalculator.DAY) {
633 nightMode = false;
634 } else {
635 nightMode = true;
636 }
637
638 // schedule next update
639 long nextUpdate = 0;
640 if (tw.mSunrise == -1 || tw.mSunset == -1) {
641 // In the case the day or night never ends the update is scheduled 12 hours later.
642 nextUpdate = currentTime + 12 * DateUtils.HOUR_IN_MILLIS;
643 } else {
644 final int mLastTwilightState = tw.mState;
645 // add some extra time to be on the save side.
646 nextUpdate += DateUtils.MINUTE_IN_MILLIS;
647 if (currentTime > tw.mSunset) {
648 // next update should be on the following day
649 tw.calculateTwilight(currentTime
650 + DateUtils.DAY_IN_MILLIS, mLocation.getLatitude(),
651 mLocation.getLongitude());
652 }
653
654 if (mLastTwilightState == TwilightCalculator.NIGHT) {
655 nextUpdate += tw.mSunrise;
656 } else {
657 nextUpdate += tw.mSunset;
658 }
659 }
660
661 Intent updateIntent = new Intent(ACTION_UPDATE_NIGHT_MODE);
662 PendingIntent pendingIntent =
663 PendingIntent.getBroadcast(mContext, 0, updateIntent, 0);
664 mAlarmManager.cancel(pendingIntent);
665 mAlarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdate, pendingIntent);
666
667 mComputedNightMode = nightMode;
668 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100669
Dianne Hackborn7299c412010-03-04 18:41:49 -0800670 @Override
671 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
672 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
673 != PackageManager.PERMISSION_GRANTED) {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100674
Dianne Hackborn7299c412010-03-04 18:41:49 -0800675 pw.println("Permission Denial: can't dump uimode service from from pid="
676 + Binder.getCallingPid()
677 + ", uid=" + Binder.getCallingUid());
678 return;
679 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100680
Dianne Hackborn7299c412010-03-04 18:41:49 -0800681 synchronized (mLock) {
682 pw.println("Current UI Mode Service state:");
683 pw.print(" mDockState="); pw.print(mDockState);
684 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
685 pw.print(" mNightMode="); pw.print(mNightMode);
686 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
687 pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
688 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800689 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
690 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800691 pw.print(" mSystemReady="); pw.println(mSystemReady);
692 if (mLocation != null) {
693 pw.print(" mLocation="); pw.println(mLocation);
694 }
695 }
696 }
697}