blob: 84790caf78806cda3eb2f1055e33df0f7d9d6cd1 [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;
Mike Lockwood924e1642010-03-05 11:56:53 -050023import android.app.KeyguardManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080024import android.app.IUiModeManager;
25import android.app.Notification;
26import android.app.NotificationManager;
27import android.app.PendingIntent;
28import android.app.StatusBarManager;
29import android.app.UiModeManager;
30import android.content.ActivityNotFoundException;
31import android.content.BroadcastReceiver;
32import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
35import android.content.pm.PackageManager;
36import android.content.res.Configuration;
37import android.location.Criteria;
38import android.location.Location;
39import android.location.LocationListener;
40import android.location.LocationManager;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050041import android.os.BatteryManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080042import android.os.Binder;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.Message;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050046import android.os.PowerManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080047import android.os.RemoteException;
48import android.os.ServiceManager;
49import android.text.format.DateUtils;
50import android.text.format.Time;
51import android.util.Slog;
52
53import java.io.FileDescriptor;
54import java.io.PrintWriter;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010055import java.util.Iterator;
Dianne Hackborn7299c412010-03-04 18:41:49 -080056
57import com.android.internal.R;
58import com.android.internal.app.DisableCarModeActivity;
59
60class UiModeManagerService extends IUiModeManager.Stub {
61 private static final String TAG = UiModeManager.class.getSimpleName();
62 private static final boolean LOG = false;
63
64 private static final String KEY_LAST_UPDATE_INTERVAL = "LAST_UPDATE_INTERVAL";
65
66 private static final int MSG_UPDATE_TWILIGHT = 0;
67 private static final int MSG_ENABLE_LOCATION_UPDATES = 1;
68
69 private static final long LOCATION_UPDATE_MS = 30 * DateUtils.MINUTE_IN_MILLIS;
70 private static final float LOCATION_UPDATE_DISTANCE_METER = 1000 * 20;
71 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MIN = 5000;
72 private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MAX = 5 * DateUtils.MINUTE_IN_MILLIS;
73 private static final double FACTOR_GMT_OFFSET_LONGITUDE = 1000.0 * 360.0 / DateUtils.DAY_IN_MILLIS;
74
75 private static final String ACTION_UPDATE_NIGHT_MODE = "com.android.server.action.UPDATE_NIGHT_MODE";
76
77 private final Context mContext;
78
79 final Object mLock = new Object();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010080
Dianne Hackborn7299c412010-03-04 18:41:49 -080081 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
82 private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010083
Dianne Hackborn7299c412010-03-04 18:41:49 -080084 private int mNightMode = UiModeManager.MODE_NIGHT_NO;
85 private boolean mCarModeEnabled = false;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050086 private boolean mCharging = false;
87 private final boolean mCarModeKeepsScreenOn;
88 private final boolean mDeskModeKeepsScreenOn;
Dianne Hackborn7299c412010-03-04 18:41:49 -080089
90 private boolean mComputedNightMode;
91 private int mCurUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080092 private int mSetUiMode = 0;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010093
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080094 private boolean mHoldingConfiguration = false;
Dianne Hackborn7299c412010-03-04 18:41:49 -080095 private Configuration mConfiguration = new Configuration();
Bernd Holzheyba9ab182010-03-12 09:30:29 +010096
Dianne Hackborn7299c412010-03-04 18:41:49 -080097 private boolean mSystemReady;
98
99 private NotificationManager mNotificationManager;
100
101 private AlarmManager mAlarmManager;
102
103 private LocationManager mLocationManager;
104 private Location mLocation;
105 private StatusBarManager mStatusBarManager;
Mike Lockwood924e1642010-03-05 11:56:53 -0500106 private KeyguardManager.KeyguardLock mKeyguardLock;
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500107 private final PowerManager.WakeLock mWakeLock;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800108
109 // The broadcast receiver which receives the result of the ordered broadcast sent when
110 // the dock state changes. The original ordered broadcast is sent with an initial result
111 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
112 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
113 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
114 @Override
115 public void onReceive(Context context, Intent intent) {
116 if (getResultCode() != Activity.RESULT_OK) {
117 return;
118 }
119
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800120 synchronized (mLock) {
121 // Launch a dock activity
122 String category;
123 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
124 // Only launch car home when car mode is enabled.
125 category = Intent.CATEGORY_CAR_DOCK;
126 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
127 category = Intent.CATEGORY_DESK_DOCK;
128 } else {
129 category = null;
130 }
131 if (category != null) {
132 intent = new Intent(Intent.ACTION_MAIN);
133 intent.addCategory(category);
134 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
135 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
136 try {
137 mContext.startActivity(intent);
138 } catch (ActivityNotFoundException e) {
139 Slog.w(TAG, e.getCause());
140 }
141 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100142
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800143 if (mHoldingConfiguration) {
144 mHoldingConfiguration = false;
145 updateConfigurationLocked();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800146 }
147 }
148 }
149 };
150
151 private final BroadcastReceiver mTwilightUpdateReceiver = new BroadcastReceiver() {
152 @Override
153 public void onReceive(Context context, Intent intent) {
154 if (isDoingNightMode() && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
155 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
156 }
157 }
158 };
159
160 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
161 @Override
162 public void onReceive(Context context, Intent intent) {
163 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
164 Intent.EXTRA_DOCK_STATE_UNDOCKED);
165 updateDockState(state);
166 }
167 };
168
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500169 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
170 @Override
171 public void onReceive(Context context, Intent intent) {
172 mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
173 synchronized (mLock) {
174 if (mSystemReady) {
175 updateLocked();
176 }
177 }
178 }
179 };
180
Dianne Hackborn7299c412010-03-04 18:41:49 -0800181 // A LocationListener to initialize the network location provider. The location updates
182 // are handled through the passive location provider.
183 private final LocationListener mEmptyLocationListener = new LocationListener() {
184 public void onLocationChanged(Location location) {
185 }
186
187 public void onProviderDisabled(String provider) {
188 }
189
190 public void onProviderEnabled(String provider) {
191 }
192
193 public void onStatusChanged(String provider, int status, Bundle extras) {
194 }
195 };
196
197 private final LocationListener mLocationListener = new LocationListener() {
198
199 public void onLocationChanged(Location location) {
200 final boolean hasMoved = hasMoved(location);
201 final boolean hasBetterAccuracy = mLocation == null
202 || location.getAccuracy() < mLocation.getAccuracy();
203 if (hasMoved || hasBetterAccuracy) {
204 synchronized (mLock) {
205 mLocation = location;
206 if (hasMoved && isDoingNightMode()
207 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
208 mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
209 }
210 }
211 }
212 }
213
214 public void onProviderDisabled(String provider) {
215 }
216
217 public void onProviderEnabled(String provider) {
218 }
219
220 public void onStatusChanged(String provider, int status, Bundle extras) {
221 }
222
223 /*
224 * The user has moved if the accuracy circles of the two locations
225 * don't overlap.
226 */
227 private boolean hasMoved(Location location) {
228 if (location == null) {
229 return false;
230 }
231 if (mLocation == null) {
232 return true;
233 }
234
235 /* if new location is older than the current one, the devices hasn't
236 * moved.
237 */
238 if (location.getTime() < mLocation.getTime()) {
239 return false;
240 }
241
242 /* Get the distance between the two points */
243 float distance = mLocation.distanceTo(location);
244
245 /* Get the total accuracy radius for both locations */
246 float totalAccuracy = mLocation.getAccuracy() + location.getAccuracy();
247
248 /* If the distance is greater than the combined accuracy of the two
249 * points then they can't overlap and hence the user has moved.
250 */
251 return distance >= totalAccuracy;
252 }
253 };
254
255 public UiModeManagerService(Context context) {
256 mContext = context;
257
258 ServiceManager.addService(Context.UI_MODE_SERVICE, this);
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100259
Dianne Hackborn7299c412010-03-04 18:41:49 -0800260 mAlarmManager =
261 (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
262 mLocationManager =
263 (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
264 mContext.registerReceiver(mTwilightUpdateReceiver,
265 new IntentFilter(ACTION_UPDATE_NIGHT_MODE));
266 mContext.registerReceiver(mDockModeReceiver,
267 new IntentFilter(Intent.ACTION_DOCK_EVENT));
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500268 mContext.registerReceiver(mBatteryReceiver,
269 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
270
271 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
272 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800273
274 mConfiguration.setToDefaults();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500275
276 mCarModeKeepsScreenOn = (context.getResources().getInteger(
277 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
278 mDeskModeKeepsScreenOn = (context.getResources().getInteger(
279 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800280 }
281
282 public void disableCarMode() {
283 synchronized (mLock) {
284 setCarModeLocked(false);
Mike Lockwood924e1642010-03-05 11:56:53 -0500285 if (mSystemReady) {
286 updateLocked();
287 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800288 }
289 }
290
291 public void enableCarMode() {
292 mContext.enforceCallingOrSelfPermission(
293 android.Manifest.permission.ENABLE_CAR_MODE,
294 "Need ENABLE_CAR_MODE permission");
295 synchronized (mLock) {
296 setCarModeLocked(true);
Mike Lockwood924e1642010-03-05 11:56:53 -0500297 if (mSystemReady) {
298 updateLocked();
299 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800300 }
301 }
302
303 public int getCurrentModeType() {
304 synchronized (mLock) {
305 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
306 }
307 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100308
Dianne Hackborn7299c412010-03-04 18:41:49 -0800309 public void setNightMode(int mode) throws RemoteException {
310 synchronized (mLock) {
311 switch (mode) {
312 case UiModeManager.MODE_NIGHT_NO:
313 case UiModeManager.MODE_NIGHT_YES:
314 case UiModeManager.MODE_NIGHT_AUTO:
315 break;
316 default:
317 throw new IllegalArgumentException("Unknown mode: " + mode);
318 }
319 if (!isDoingNightMode()) {
320 return;
321 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100322
Dianne Hackborn7299c412010-03-04 18:41:49 -0800323 if (mNightMode != mode) {
324 mNightMode = mode;
325 updateLocked();
326 }
327 }
328 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100329
Dianne Hackborn7299c412010-03-04 18:41:49 -0800330 public int getNightMode() throws RemoteException {
331 return mNightMode;
332 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100333
Dianne Hackborn7299c412010-03-04 18:41:49 -0800334 void systemReady() {
335 synchronized (mLock) {
336 mSystemReady = true;
337 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
338 updateLocked();
339 mHandler.sendEmptyMessage(MSG_ENABLE_LOCATION_UPDATES);
340 }
341 }
342
343 boolean isDoingNightMode() {
344 return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
345 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100346
Dianne Hackborn7299c412010-03-04 18:41:49 -0800347 void setCarModeLocked(boolean enabled) {
348 if (mCarModeEnabled != enabled) {
349 mCarModeEnabled = enabled;
Mike Lockwood924e1642010-03-05 11:56:53 -0500350
351 // Disable keyguard when in car mode
352 if (mKeyguardLock == null) {
353 KeyguardManager km =
354 (KeyguardManager)mContext.getSystemService(Context.KEYGUARD_SERVICE);
355 if (km != null) {
356 mKeyguardLock = km.newKeyguardLock(TAG);
357 }
358 }
359 if (mKeyguardLock != null) {
Tobias Haamel9f938812010-03-08 11:21:59 +0100360 long ident = Binder.clearCallingIdentity();
Mike Lockwood924e1642010-03-05 11:56:53 -0500361 if (enabled) {
362 mKeyguardLock.disableKeyguard();
363 } else {
364 mKeyguardLock.reenableKeyguard();
365 }
Tobias Haamel9f938812010-03-08 11:21:59 +0100366 Binder.restoreCallingIdentity(ident);
Mike Lockwood924e1642010-03-05 11:56:53 -0500367 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800368 }
369 }
370
371 void updateDockState(int newState) {
372 synchronized (mLock) {
373 if (newState != mDockState) {
374 mDockState = newState;
Mike Lockwood924e1642010-03-05 11:56:53 -0500375 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800376 if (mSystemReady) {
377 updateLocked();
378 }
379 }
380 }
381 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500382
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800383 final void updateConfigurationLocked() {
384 int uiMode = 0;
385 if (mCarModeEnabled) {
386 uiMode = Configuration.UI_MODE_TYPE_CAR;
387 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
388 uiMode = Configuration.UI_MODE_TYPE_DESK;
389 }
390 if (uiMode != 0) {
391 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
392 updateTwilightLocked();
393 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
394 : Configuration.UI_MODE_NIGHT_NO;
395 } else {
396 uiMode |= mNightMode << 4;
397 }
398 } else {
399 // Disabling the car mode clears the night mode.
400 uiMode = Configuration.UI_MODE_TYPE_NORMAL |
401 Configuration.UI_MODE_NIGHT_NO;
402 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100403
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800404 mCurUiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100405
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800406 if (!mHoldingConfiguration && uiMode != mSetUiMode) {
407 mSetUiMode = uiMode;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100408
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800409 try {
410 final IActivityManager am = ActivityManagerNative.getDefault();
411 mConfiguration.uiMode = uiMode;
412 am.updateConfiguration(mConfiguration);
413 } catch (RemoteException e) {
414 Slog.w(TAG, "Failure communicating with activity manager", e);
415 }
416 }
417 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100418
Dianne Hackborn7299c412010-03-04 18:41:49 -0800419 final void updateLocked() {
420 long ident = Binder.clearCallingIdentity();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100421
Dianne Hackborn7299c412010-03-04 18:41:49 -0800422 try {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800423 String action = null;
424 String oldAction = null;
425 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
426 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
427 } else if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_DESK) {
428 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
429 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100430
Dianne Hackborn7299c412010-03-04 18:41:49 -0800431 if (mCarModeEnabled) {
432 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
433 adjustStatusBarCarModeLocked();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100434
Dianne Hackborn7299c412010-03-04 18:41:49 -0800435 if (oldAction != null) {
436 mContext.sendBroadcast(new Intent(oldAction));
437 }
438 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
439 action = UiModeManager.ACTION_ENTER_CAR_MODE;
440 }
441 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
442 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_DESK) {
443 if (oldAction != null) {
444 mContext.sendBroadcast(new Intent(oldAction));
445 }
446 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_DESK;
447 action = UiModeManager.ACTION_ENTER_DESK_MODE;
448 }
449 } else {
450 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
451 adjustStatusBarCarModeLocked();
452 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100453
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 Hackbornb8b11a02010-03-10 15:53:11 -0800473 updateConfigurationLocked();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500474
475 // keep screen on when charging and in car mode
476 boolean keepScreenOn = mCharging &&
477 ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
478 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
479 if (keepScreenOn != mWakeLock.isHeld()) {
480 if (keepScreenOn) {
481 mWakeLock.acquire();
482 } else {
483 mWakeLock.release();
484 }
485 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800486 } finally {
487 Binder.restoreCallingIdentity(ident);
488 }
489 }
490
491 private void adjustStatusBarCarModeLocked() {
492 if (mStatusBarManager == null) {
493 mStatusBarManager = (StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
494 }
495
496 // Fear not: StatusBarService manages a list of requests to disable
497 // features of the status bar; these are ORed together to form the
498 // active disabled list. So if (for example) the device is locked and
499 // the status bar should be totally disabled, the calls below will
500 // have no effect until the device is unlocked.
501 if (mStatusBarManager != null) {
502 mStatusBarManager.disable(mCarModeEnabled
503 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
504 : StatusBarManager.DISABLE_NONE);
505 }
506
507 if (mNotificationManager == null) {
508 mNotificationManager = (NotificationManager)
509 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
510 }
511
512 if (mNotificationManager != null) {
513 if (mCarModeEnabled) {
514 Intent carModeOffIntent = new Intent(mContext, DisableCarModeActivity.class);
515
516 Notification n = new Notification();
517 n.icon = R.drawable.stat_notify_car_mode;
518 n.defaults = Notification.DEFAULT_LIGHTS;
519 n.flags = Notification.FLAG_ONGOING_EVENT;
520 n.when = 0;
521 n.setLatestEventInfo(
522 mContext,
523 mContext.getString(R.string.car_mode_disable_notification_title),
524 mContext.getString(R.string.car_mode_disable_notification_message),
525 PendingIntent.getActivity(mContext, 0, carModeOffIntent, 0));
526 mNotificationManager.notify(0, n);
527 } else {
528 mNotificationManager.cancel(0);
529 }
530 }
531 }
532
533 private final Handler mHandler = new Handler() {
534
535 boolean mPassiveListenerEnabled;
536 boolean mNetworkListenerEnabled;
537
538 @Override
539 public void handleMessage(Message msg) {
540 switch (msg.what) {
541 case MSG_UPDATE_TWILIGHT:
542 synchronized (mLock) {
543 if (isDoingNightMode() && mLocation != null
544 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
545 updateTwilightLocked();
546 updateLocked();
547 }
548 }
549 break;
550 case MSG_ENABLE_LOCATION_UPDATES:
551 // enable network provider to receive at least location updates for a given
552 // distance.
553 boolean networkLocationEnabled;
554 try {
555 networkLocationEnabled =
556 mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
557 } catch (Exception e) {
558 // we may get IllegalArgumentException if network location provider
559 // does not exist or is not yet installed.
560 networkLocationEnabled = false;
561 }
562 if (!mNetworkListenerEnabled && networkLocationEnabled) {
563 mNetworkListenerEnabled = true;
564 mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
565 LOCATION_UPDATE_MS, 0, mEmptyLocationListener);
566
567 if (mLocation == null) {
568 retrieveLocation();
569 }
570 synchronized (mLock) {
571 if (isDoingNightMode() && mLocation != null
572 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
573 updateTwilightLocked();
574 updateLocked();
575 }
576 }
577 }
578 // enable passive provider to receive updates from location fixes (gps
579 // and network).
580 boolean passiveLocationEnabled;
581 try {
582 passiveLocationEnabled =
583 mLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
584 } catch (Exception e) {
585 // we may get IllegalArgumentException if passive location provider
586 // does not exist or is not yet installed.
587 passiveLocationEnabled = false;
588 }
589 if (!mPassiveListenerEnabled && passiveLocationEnabled) {
590 mPassiveListenerEnabled = true;
591 mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
592 0, LOCATION_UPDATE_DISTANCE_METER , mLocationListener);
593 }
594 if (!(mNetworkListenerEnabled && mPassiveListenerEnabled)) {
595 long interval = msg.getData().getLong(KEY_LAST_UPDATE_INTERVAL);
596 interval *= 1.5;
597 if (interval == 0) {
598 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MIN;
599 } else if (interval > LOCATION_UPDATE_ENABLE_INTERVAL_MAX) {
600 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MAX;
601 }
602 Bundle bundle = new Bundle();
603 bundle.putLong(KEY_LAST_UPDATE_INTERVAL, interval);
604 Message newMsg = mHandler.obtainMessage(MSG_ENABLE_LOCATION_UPDATES);
605 newMsg.setData(bundle);
606 mHandler.sendMessageDelayed(newMsg, interval);
607 }
608 break;
609 }
610 }
611
612 private void retrieveLocation() {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100613 Location location = null;
614 final Iterator<String> providers =
615 mLocationManager.getProviders(new Criteria(), true).iterator();
616 while (providers.hasNext()) {
617 final Location lastKnownLocation =
618 mLocationManager.getLastKnownLocation(providers.next());
619 // pick the most recent location
620 if (location == null || (lastKnownLocation != null &&
621 location.getTime() < lastKnownLocation.getTime())) {
622 location = lastKnownLocation;
623 }
624 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800625 // In the case there is no location available (e.g. GPS fix or network location
626 // is not available yet), the longitude of the location is estimated using the timezone,
627 // latitude and accuracy are set to get a good average.
628 if (location == null) {
629 Time currentTime = new Time();
630 currentTime.set(System.currentTimeMillis());
631 double lngOffset = FACTOR_GMT_OFFSET_LONGITUDE *
632 (currentTime.gmtoff - (currentTime.isDst > 0 ? 3600 : 0));
633 location = new Location("fake");
634 location.setLongitude(lngOffset);
635 location.setLatitude(0);
636 location.setAccuracy(417000.0f);
637 location.setTime(System.currentTimeMillis());
638 }
639 synchronized (mLock) {
640 mLocation = location;
641 }
642 }
643 };
644
645 void updateTwilightLocked() {
646 if (mLocation == null) {
647 return;
648 }
649 final long currentTime = System.currentTimeMillis();
650 boolean nightMode;
651 // calculate current twilight
652 TwilightCalculator tw = new TwilightCalculator();
653 tw.calculateTwilight(currentTime,
654 mLocation.getLatitude(), mLocation.getLongitude());
655 if (tw.mState == TwilightCalculator.DAY) {
656 nightMode = false;
657 } else {
658 nightMode = true;
659 }
660
661 // schedule next update
662 long nextUpdate = 0;
663 if (tw.mSunrise == -1 || tw.mSunset == -1) {
664 // In the case the day or night never ends the update is scheduled 12 hours later.
665 nextUpdate = currentTime + 12 * DateUtils.HOUR_IN_MILLIS;
666 } else {
667 final int mLastTwilightState = tw.mState;
668 // add some extra time to be on the save side.
669 nextUpdate += DateUtils.MINUTE_IN_MILLIS;
670 if (currentTime > tw.mSunset) {
671 // next update should be on the following day
672 tw.calculateTwilight(currentTime
673 + DateUtils.DAY_IN_MILLIS, mLocation.getLatitude(),
674 mLocation.getLongitude());
675 }
676
677 if (mLastTwilightState == TwilightCalculator.NIGHT) {
678 nextUpdate += tw.mSunrise;
679 } else {
680 nextUpdate += tw.mSunset;
681 }
682 }
683
684 Intent updateIntent = new Intent(ACTION_UPDATE_NIGHT_MODE);
685 PendingIntent pendingIntent =
686 PendingIntent.getBroadcast(mContext, 0, updateIntent, 0);
687 mAlarmManager.cancel(pendingIntent);
688 mAlarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdate, pendingIntent);
689
690 mComputedNightMode = nightMode;
691 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100692
Dianne Hackborn7299c412010-03-04 18:41:49 -0800693 @Override
694 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
695 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
696 != PackageManager.PERMISSION_GRANTED) {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100697
Dianne Hackborn7299c412010-03-04 18:41:49 -0800698 pw.println("Permission Denial: can't dump uimode service from from pid="
699 + Binder.getCallingPid()
700 + ", uid=" + Binder.getCallingUid());
701 return;
702 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100703
Dianne Hackborn7299c412010-03-04 18:41:49 -0800704 synchronized (mLock) {
705 pw.println("Current UI Mode Service state:");
706 pw.print(" mDockState="); pw.print(mDockState);
707 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
708 pw.print(" mNightMode="); pw.print(mNightMode);
709 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
710 pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
711 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800712 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
713 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800714 pw.print(" mSystemReady="); pw.println(mSystemReady);
715 if (mLocation != null) {
716 pw.print(" mLocation="); pw.println(mLocation);
717 }
718 }
719 }
720}