blob: 37a3cdf1bdf7d95adc334d94da77e023471736e1 [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) {
Tobias Haamel780b2602010-03-15 12:54:45 +0100426 adjustStatusBarCarModeLocked();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800427 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
428 } else if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_DESK) {
429 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
430 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100431
Dianne Hackborn7299c412010-03-04 18:41:49 -0800432 if (mCarModeEnabled) {
433 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
434 adjustStatusBarCarModeLocked();
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100435
Dianne Hackborn7299c412010-03-04 18:41:49 -0800436 if (oldAction != null) {
437 mContext.sendBroadcast(new Intent(oldAction));
438 }
439 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
440 action = UiModeManager.ACTION_ENTER_CAR_MODE;
441 }
442 } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
443 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_DESK) {
444 if (oldAction != null) {
445 mContext.sendBroadcast(new Intent(oldAction));
446 }
447 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_DESK;
448 action = UiModeManager.ACTION_ENTER_DESK_MODE;
449 }
450 } else {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800451 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
452 action = oldAction;
453 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100454
Dianne Hackborn7299c412010-03-04 18:41:49 -0800455 if (action != null) {
456 // Send the ordered broadcast; the result receiver will receive after all
457 // broadcasts have been sent. If any broadcast receiver changes the result
458 // code from the initial value of RESULT_OK, then the result receiver will
459 // not launch the corresponding dock application. This gives apps a chance
460 // to override the behavior and stay in their app even when the device is
461 // placed into a dock.
462 mContext.sendOrderedBroadcast(new Intent(action), null,
463 mResultReceiver, null, Activity.RESULT_OK, null, null);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800464 // Attempting to make this transition a little more clean, we are going
465 // to hold off on doing a configuration change until we have finished
466 // the broacast and started the home activity.
467 mHoldingConfiguration = true;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800468 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100469
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800470 updateConfigurationLocked();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500471
472 // keep screen on when charging and in car mode
473 boolean keepScreenOn = mCharging &&
474 ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
475 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
476 if (keepScreenOn != mWakeLock.isHeld()) {
477 if (keepScreenOn) {
478 mWakeLock.acquire();
479 } else {
480 mWakeLock.release();
481 }
482 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800483 } finally {
484 Binder.restoreCallingIdentity(ident);
485 }
486 }
487
488 private void adjustStatusBarCarModeLocked() {
489 if (mStatusBarManager == null) {
490 mStatusBarManager = (StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
491 }
492
493 // Fear not: StatusBarService manages a list of requests to disable
494 // features of the status bar; these are ORed together to form the
495 // active disabled list. So if (for example) the device is locked and
496 // the status bar should be totally disabled, the calls below will
497 // have no effect until the device is unlocked.
498 if (mStatusBarManager != null) {
499 mStatusBarManager.disable(mCarModeEnabled
500 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
501 : StatusBarManager.DISABLE_NONE);
502 }
503
504 if (mNotificationManager == null) {
505 mNotificationManager = (NotificationManager)
506 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
507 }
508
509 if (mNotificationManager != null) {
510 if (mCarModeEnabled) {
511 Intent carModeOffIntent = new Intent(mContext, DisableCarModeActivity.class);
512
513 Notification n = new Notification();
514 n.icon = R.drawable.stat_notify_car_mode;
515 n.defaults = Notification.DEFAULT_LIGHTS;
516 n.flags = Notification.FLAG_ONGOING_EVENT;
517 n.when = 0;
518 n.setLatestEventInfo(
519 mContext,
520 mContext.getString(R.string.car_mode_disable_notification_title),
521 mContext.getString(R.string.car_mode_disable_notification_message),
522 PendingIntent.getActivity(mContext, 0, carModeOffIntent, 0));
523 mNotificationManager.notify(0, n);
524 } else {
525 mNotificationManager.cancel(0);
526 }
527 }
528 }
529
530 private final Handler mHandler = new Handler() {
531
532 boolean mPassiveListenerEnabled;
533 boolean mNetworkListenerEnabled;
534
535 @Override
536 public void handleMessage(Message msg) {
537 switch (msg.what) {
538 case MSG_UPDATE_TWILIGHT:
539 synchronized (mLock) {
540 if (isDoingNightMode() && mLocation != null
541 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
542 updateTwilightLocked();
543 updateLocked();
544 }
545 }
546 break;
547 case MSG_ENABLE_LOCATION_UPDATES:
548 // enable network provider to receive at least location updates for a given
549 // distance.
550 boolean networkLocationEnabled;
551 try {
552 networkLocationEnabled =
553 mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
554 } catch (Exception e) {
555 // we may get IllegalArgumentException if network location provider
556 // does not exist or is not yet installed.
557 networkLocationEnabled = false;
558 }
559 if (!mNetworkListenerEnabled && networkLocationEnabled) {
560 mNetworkListenerEnabled = true;
561 mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
562 LOCATION_UPDATE_MS, 0, mEmptyLocationListener);
563
564 if (mLocation == null) {
565 retrieveLocation();
566 }
567 synchronized (mLock) {
568 if (isDoingNightMode() && mLocation != null
569 && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
570 updateTwilightLocked();
571 updateLocked();
572 }
573 }
574 }
575 // enable passive provider to receive updates from location fixes (gps
576 // and network).
577 boolean passiveLocationEnabled;
578 try {
579 passiveLocationEnabled =
580 mLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
581 } catch (Exception e) {
582 // we may get IllegalArgumentException if passive location provider
583 // does not exist or is not yet installed.
584 passiveLocationEnabled = false;
585 }
586 if (!mPassiveListenerEnabled && passiveLocationEnabled) {
587 mPassiveListenerEnabled = true;
588 mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
589 0, LOCATION_UPDATE_DISTANCE_METER , mLocationListener);
590 }
591 if (!(mNetworkListenerEnabled && mPassiveListenerEnabled)) {
592 long interval = msg.getData().getLong(KEY_LAST_UPDATE_INTERVAL);
593 interval *= 1.5;
594 if (interval == 0) {
595 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MIN;
596 } else if (interval > LOCATION_UPDATE_ENABLE_INTERVAL_MAX) {
597 interval = LOCATION_UPDATE_ENABLE_INTERVAL_MAX;
598 }
599 Bundle bundle = new Bundle();
600 bundle.putLong(KEY_LAST_UPDATE_INTERVAL, interval);
601 Message newMsg = mHandler.obtainMessage(MSG_ENABLE_LOCATION_UPDATES);
602 newMsg.setData(bundle);
603 mHandler.sendMessageDelayed(newMsg, interval);
604 }
605 break;
606 }
607 }
608
609 private void retrieveLocation() {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100610 Location location = null;
611 final Iterator<String> providers =
612 mLocationManager.getProviders(new Criteria(), true).iterator();
613 while (providers.hasNext()) {
614 final Location lastKnownLocation =
615 mLocationManager.getLastKnownLocation(providers.next());
616 // pick the most recent location
617 if (location == null || (lastKnownLocation != null &&
618 location.getTime() < lastKnownLocation.getTime())) {
619 location = lastKnownLocation;
620 }
621 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800622 // In the case there is no location available (e.g. GPS fix or network location
623 // is not available yet), the longitude of the location is estimated using the timezone,
624 // latitude and accuracy are set to get a good average.
625 if (location == null) {
626 Time currentTime = new Time();
627 currentTime.set(System.currentTimeMillis());
628 double lngOffset = FACTOR_GMT_OFFSET_LONGITUDE *
629 (currentTime.gmtoff - (currentTime.isDst > 0 ? 3600 : 0));
630 location = new Location("fake");
631 location.setLongitude(lngOffset);
632 location.setLatitude(0);
633 location.setAccuracy(417000.0f);
634 location.setTime(System.currentTimeMillis());
635 }
636 synchronized (mLock) {
637 mLocation = location;
638 }
639 }
640 };
641
642 void updateTwilightLocked() {
643 if (mLocation == null) {
644 return;
645 }
646 final long currentTime = System.currentTimeMillis();
647 boolean nightMode;
648 // calculate current twilight
649 TwilightCalculator tw = new TwilightCalculator();
650 tw.calculateTwilight(currentTime,
651 mLocation.getLatitude(), mLocation.getLongitude());
652 if (tw.mState == TwilightCalculator.DAY) {
653 nightMode = false;
654 } else {
655 nightMode = true;
656 }
657
658 // schedule next update
659 long nextUpdate = 0;
660 if (tw.mSunrise == -1 || tw.mSunset == -1) {
661 // In the case the day or night never ends the update is scheduled 12 hours later.
662 nextUpdate = currentTime + 12 * DateUtils.HOUR_IN_MILLIS;
663 } else {
664 final int mLastTwilightState = tw.mState;
665 // add some extra time to be on the save side.
666 nextUpdate += DateUtils.MINUTE_IN_MILLIS;
667 if (currentTime > tw.mSunset) {
668 // next update should be on the following day
669 tw.calculateTwilight(currentTime
670 + DateUtils.DAY_IN_MILLIS, mLocation.getLatitude(),
671 mLocation.getLongitude());
672 }
673
674 if (mLastTwilightState == TwilightCalculator.NIGHT) {
675 nextUpdate += tw.mSunrise;
676 } else {
677 nextUpdate += tw.mSunset;
678 }
679 }
680
681 Intent updateIntent = new Intent(ACTION_UPDATE_NIGHT_MODE);
682 PendingIntent pendingIntent =
683 PendingIntent.getBroadcast(mContext, 0, updateIntent, 0);
684 mAlarmManager.cancel(pendingIntent);
685 mAlarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdate, pendingIntent);
686
687 mComputedNightMode = nightMode;
688 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100689
Dianne Hackborn7299c412010-03-04 18:41:49 -0800690 @Override
691 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
692 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
693 != PackageManager.PERMISSION_GRANTED) {
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100694
Dianne Hackborn7299c412010-03-04 18:41:49 -0800695 pw.println("Permission Denial: can't dump uimode service from from pid="
696 + Binder.getCallingPid()
697 + ", uid=" + Binder.getCallingUid());
698 return;
699 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100700
Dianne Hackborn7299c412010-03-04 18:41:49 -0800701 synchronized (mLock) {
702 pw.println("Current UI Mode Service state:");
703 pw.print(" mDockState="); pw.print(mDockState);
704 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
705 pw.print(" mNightMode="); pw.print(mNightMode);
706 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
707 pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
708 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800709 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
710 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800711 pw.print(" mSystemReady="); pw.println(mSystemReady);
712 if (mLocation != null) {
713 pw.print(" mLocation="); pw.println(mLocation);
714 }
715 }
716 }
717}