UiModeManagerService.java revision 69a1da4ddec90db501a54f0c4de94e9557aebd2e
1/*
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.IUiModeManager;
23import android.app.Notification;
24import android.app.NotificationManager;
25import android.app.PendingIntent;
26import android.app.StatusBarManager;
27import android.app.UiModeManager;
28import android.content.ActivityNotFoundException;
29import 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;
39import android.os.BatteryManager;
40import android.os.Binder;
41import android.os.Bundle;
42import android.os.Handler;
43import android.os.Message;
44import android.os.PowerManager;
45import android.os.RemoteException;
46import android.os.ServiceManager;
47import android.os.SystemClock;
48import android.provider.Settings;
49import android.text.format.DateUtils;
50import android.text.format.Time;
51import android.util.Slog;
52
53import java.io.FileDescriptor;
54import java.io.PrintWriter;
55import java.util.Iterator;
56
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    private static final int MSG_GET_NEW_LOCATION_UPDATE = 2;
69
70    private static final long LOCATION_UPDATE_MS = 24 * DateUtils.HOUR_IN_MILLIS;
71    private static final long MIN_LOCATION_UPDATE_MS = 30 * DateUtils.MINUTE_IN_MILLIS;
72    private static final float LOCATION_UPDATE_DISTANCE_METER = 1000 * 20;
73    private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MIN = 5000;
74    private static final long LOCATION_UPDATE_ENABLE_INTERVAL_MAX = 15 * DateUtils.MINUTE_IN_MILLIS;
75    private static final double FACTOR_GMT_OFFSET_LONGITUDE = 1000.0 * 360.0 / DateUtils.DAY_IN_MILLIS;
76
77    private static final String ACTION_UPDATE_NIGHT_MODE = "com.android.server.action.UPDATE_NIGHT_MODE";
78
79    private final Context mContext;
80
81    final Object mLock = new Object();
82
83    private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
84    private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
85
86    private int mNightMode = UiModeManager.MODE_NIGHT_NO;
87    private boolean mCarModeEnabled = false;
88    private boolean mCharging = false;
89    private final boolean mCarModeKeepsScreenOn;
90    private final boolean mDeskModeKeepsScreenOn;
91
92    private boolean mComputedNightMode;
93    private int mCurUiMode = 0;
94    private int mSetUiMode = 0;
95
96    private boolean mHoldingConfiguration = false;
97    private Configuration mConfiguration = new Configuration();
98
99    private boolean mSystemReady;
100
101    private NotificationManager mNotificationManager;
102
103    private AlarmManager mAlarmManager;
104
105    private LocationManager mLocationManager;
106    private Location mLocation;
107    private StatusBarManager mStatusBarManager;
108    private final PowerManager.WakeLock mWakeLock;
109
110    static Intent buildHomeIntent(String category) {
111        Intent intent = new Intent(Intent.ACTION_MAIN);
112        intent.addCategory(category);
113        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
114                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
115        return intent;
116    }
117
118    // The broadcast receiver which receives the result of the ordered broadcast sent when
119    // the dock state changes. The original ordered broadcast is sent with an initial result
120    // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
121    // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
122    private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
123        @Override
124        public void onReceive(Context context, Intent intent) {
125            if (getResultCode() != Activity.RESULT_OK) {
126                if (LOG) {
127                    Slog.v(TAG, "Handling broadcast result for action " + intent.getAction()
128                            + ": canceled: " + getResultCode());
129                }
130                return;
131            }
132
133            final int  enableFlags = intent.getIntExtra("enableFlags", 0);
134            final int  disableFlags = intent.getIntExtra("disableFlags", 0);
135
136            synchronized (mLock) {
137                // Launch a dock activity
138                String category = null;
139                if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
140                    // Only launch car home when car mode is enabled and the caller
141                    // has asked us to switch to it.
142                    if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
143                        category = Intent.CATEGORY_CAR_DOCK;
144                    }
145                } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
146                    // Only launch car home when desk mode is enabled and the caller
147                    // has asked us to switch to it.  Currently re-using the car
148                    // mode flag since we don't have a formal API for "desk mode".
149                    if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
150                        category = Intent.CATEGORY_DESK_DOCK;
151                    }
152                } else {
153                    // Launch the standard home app if requested.
154                    if ((disableFlags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
155                        category = Intent.CATEGORY_HOME;
156                    }
157                }
158
159                if (LOG) {
160                    Slog.v(TAG, String.format(
161                        "Handling broadcast result for action %s: enable=0x%08x disable=0x%08x category=%s",
162                        intent.getAction(), enableFlags, disableFlags, category));
163                }
164
165                if (category != null) {
166                    // This is the new activity that will serve as home while
167                    // we are in care mode.
168                    Intent homeIntent = buildHomeIntent(category);
169
170                    // Now we are going to be careful about switching the
171                    // configuration and starting the activity -- we need to
172                    // do this in a specific order under control of the
173                    // activity manager, to do it cleanly.  So compute the
174                    // new config, but don't set it yet, and let the
175                    // activity manager take care of both the start and config
176                    // change.
177                    Configuration newConfig = null;
178                    if (mHoldingConfiguration) {
179                        mHoldingConfiguration = false;
180                        updateConfigurationLocked(false);
181                        newConfig = mConfiguration;
182                    }
183                    try {
184                        ActivityManagerNative.getDefault().startActivityWithConfig(
185                                null, homeIntent, null, null, 0, null, null, 0, false, false,
186                                newConfig);
187                        mHoldingConfiguration = false;
188                    } catch (RemoteException e) {
189                        Slog.w(TAG, e.getCause());
190                    }
191                }
192
193                if (mHoldingConfiguration) {
194                    mHoldingConfiguration = false;
195                    updateConfigurationLocked(true);
196                }
197            }
198        }
199    };
200
201    private final BroadcastReceiver mTwilightUpdateReceiver = new BroadcastReceiver() {
202        @Override
203        public void onReceive(Context context, Intent intent) {
204            if (isDoingNightMode() && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
205                mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
206            }
207        }
208    };
209
210    private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
211        @Override
212        public void onReceive(Context context, Intent intent) {
213            int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
214                    Intent.EXTRA_DOCK_STATE_UNDOCKED);
215            updateDockState(state);
216        }
217    };
218
219    private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
220        @Override
221        public void onReceive(Context context, Intent intent) {
222            mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
223            synchronized (mLock) {
224                if (mSystemReady) {
225                    updateLocked(0, 0);
226                }
227            }
228        }
229    };
230
231    private final BroadcastReceiver mUpdateLocationReceiver = new BroadcastReceiver() {
232        @Override
233        public void onReceive(Context context, Intent intent) {
234            if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())) {
235                if (!intent.getBooleanExtra("state", false)) {
236                    // Airplane mode is now off!
237                    mHandler.sendEmptyMessage(MSG_GET_NEW_LOCATION_UPDATE);
238                }
239            } else {
240                // Time zone has changed!
241                mHandler.sendEmptyMessage(MSG_GET_NEW_LOCATION_UPDATE);
242            }
243        }
244    };
245
246    // A LocationListener to initialize the network location provider. The location updates
247    // are handled through the passive location provider.
248    private final LocationListener mEmptyLocationListener =  new LocationListener() {
249        public void onLocationChanged(Location location) {
250        }
251
252        public void onProviderDisabled(String provider) {
253        }
254
255        public void onProviderEnabled(String provider) {
256        }
257
258        public void onStatusChanged(String provider, int status, Bundle extras) {
259        }
260    };
261
262    private final LocationListener mLocationListener = new LocationListener() {
263
264        public void onLocationChanged(Location location) {
265            final boolean hasMoved = hasMoved(location);
266            final boolean hasBetterAccuracy = mLocation == null
267                    || location.getAccuracy() < mLocation.getAccuracy();
268            if (hasMoved || hasBetterAccuracy) {
269                synchronized (mLock) {
270                    mLocation = location;
271                    if (hasMoved && isDoingNightMode()
272                            && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
273                        mHandler.sendEmptyMessage(MSG_UPDATE_TWILIGHT);
274                    }
275                }
276            }
277        }
278
279        public void onProviderDisabled(String provider) {
280        }
281
282        public void onProviderEnabled(String provider) {
283        }
284
285        public void onStatusChanged(String provider, int status, Bundle extras) {
286        }
287
288        /*
289         * The user has moved if the accuracy circles of the two locations
290         * don't overlap.
291         */
292        private boolean hasMoved(Location location) {
293            if (location == null) {
294                return false;
295            }
296            if (mLocation == null) {
297                return true;
298            }
299
300            /* if new location is older than the current one, the devices hasn't
301             * moved.
302             */
303            if (location.getTime() < mLocation.getTime()) {
304                return false;
305            }
306
307            /* Get the distance between the two points */
308            float distance = mLocation.distanceTo(location);
309
310            /* Get the total accuracy radius for both locations */
311            float totalAccuracy = mLocation.getAccuracy() + location.getAccuracy();
312
313            /* If the distance is greater than the combined accuracy of the two
314             * points then they can't overlap and hence the user has moved.
315             */
316            return distance >= totalAccuracy;
317        }
318    };
319
320    public UiModeManagerService(Context context) {
321        mContext = context;
322
323        ServiceManager.addService(Context.UI_MODE_SERVICE, this);
324
325        mAlarmManager =
326            (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
327        mLocationManager =
328            (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
329        mContext.registerReceiver(mTwilightUpdateReceiver,
330                new IntentFilter(ACTION_UPDATE_NIGHT_MODE));
331        mContext.registerReceiver(mDockModeReceiver,
332                new IntentFilter(Intent.ACTION_DOCK_EVENT));
333        mContext.registerReceiver(mBatteryReceiver,
334                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
335        IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
336        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
337        mContext.registerReceiver(mUpdateLocationReceiver, filter);
338
339        PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
340        mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
341
342        mConfiguration.setToDefaults();
343
344        mCarModeKeepsScreenOn = (context.getResources().getInteger(
345                com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
346        mDeskModeKeepsScreenOn = (context.getResources().getInteger(
347                com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
348
349        mNightMode = Settings.Secure.getInt(mContext.getContentResolver(),
350                Settings.Secure.UI_NIGHT_MODE, UiModeManager.MODE_NIGHT_AUTO);
351    }
352
353    public void disableCarMode(int flags) {
354        synchronized (mLock) {
355            setCarModeLocked(false);
356            if (mSystemReady) {
357                updateLocked(0, flags);
358            }
359        }
360    }
361
362    public void enableCarMode(int flags) {
363        synchronized (mLock) {
364            setCarModeLocked(true);
365            if (mSystemReady) {
366                updateLocked(flags, 0);
367            }
368        }
369    }
370
371    public int getCurrentModeType() {
372        synchronized (mLock) {
373            return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
374        }
375    }
376
377    public void setNightMode(int mode) throws RemoteException {
378        synchronized (mLock) {
379            switch (mode) {
380                case UiModeManager.MODE_NIGHT_NO:
381                case UiModeManager.MODE_NIGHT_YES:
382                case UiModeManager.MODE_NIGHT_AUTO:
383                    break;
384                default:
385                    throw new IllegalArgumentException("Unknown mode: " + mode);
386            }
387            if (!isDoingNightMode()) {
388                return;
389            }
390
391            if (mNightMode != mode) {
392                long ident = Binder.clearCallingIdentity();
393                Settings.Secure.putInt(mContext.getContentResolver(),
394                        Settings.Secure.UI_NIGHT_MODE, mode);
395                Binder.restoreCallingIdentity(ident);
396                mNightMode = mode;
397                updateLocked(0, 0);
398            }
399        }
400    }
401
402    public int getNightMode() throws RemoteException {
403        return mNightMode;
404    }
405
406    void systemReady() {
407        synchronized (mLock) {
408            mSystemReady = true;
409            mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
410            updateLocked(0, 0);
411            mHandler.sendEmptyMessage(MSG_ENABLE_LOCATION_UPDATES);
412        }
413    }
414
415    boolean isDoingNightMode() {
416        return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
417    }
418
419    void setCarModeLocked(boolean enabled) {
420        if (mCarModeEnabled != enabled) {
421            mCarModeEnabled = enabled;
422        }
423    }
424
425    void updateDockState(int newState) {
426        synchronized (mLock) {
427            if (newState != mDockState) {
428                mDockState = newState;
429                setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR);
430                if (mSystemReady) {
431                    updateLocked(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME, 0);
432                }
433            }
434        }
435    }
436
437    final static boolean isDeskDockState(int state) {
438        switch (state) {
439            case Intent.EXTRA_DOCK_STATE_DESK:
440            case Intent.EXTRA_DOCK_STATE_LE_DESK:
441            case Intent.EXTRA_DOCK_STATE_HE_DESK:
442                return true;
443            default:
444                return false;
445        }
446    }
447
448    final void updateConfigurationLocked(boolean sendIt) {
449        int uiMode = Configuration.UI_MODE_TYPE_NORMAL;
450        if (mCarModeEnabled) {
451            uiMode = Configuration.UI_MODE_TYPE_CAR;
452        } else if (isDeskDockState(mDockState)) {
453            uiMode = Configuration.UI_MODE_TYPE_DESK;
454        }
455        if (mCarModeEnabled) {
456            if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
457                updateTwilightLocked();
458                uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
459                        : Configuration.UI_MODE_NIGHT_NO;
460            } else {
461                uiMode |= mNightMode << 4;
462            }
463        } else {
464            // Disabling the car mode clears the night mode.
465            uiMode = (uiMode & ~Configuration.UI_MODE_NIGHT_MASK) | Configuration.UI_MODE_NIGHT_NO;
466        }
467
468        if (LOG) {
469            Slog.d(TAG,
470                "updateConfigurationLocked: mDockState=" + mDockState
471                + "; mCarMode=" + mCarModeEnabled
472                + "; mNightMode=" + mNightMode
473                + "; uiMode=" + uiMode);
474        }
475
476        mCurUiMode = uiMode;
477
478        if (!mHoldingConfiguration && uiMode != mSetUiMode) {
479            mSetUiMode = uiMode;
480            mConfiguration.uiMode = uiMode;
481
482            if (sendIt) {
483                try {
484                    ActivityManagerNative.getDefault().updateConfiguration(mConfiguration);
485                } catch (RemoteException e) {
486                    Slog.w(TAG, "Failure communicating with activity manager", e);
487                }
488            }
489        }
490    }
491
492    final void updateLocked(int enableFlags, int disableFlags) {
493        long ident = Binder.clearCallingIdentity();
494
495        try {
496            String action = null;
497            String oldAction = null;
498            if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
499                adjustStatusBarCarModeLocked();
500                oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
501            } else if (isDeskDockState(mLastBroadcastState)) {
502                oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
503            }
504
505            if (mCarModeEnabled) {
506                if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
507                    adjustStatusBarCarModeLocked();
508
509                    if (oldAction != null) {
510                        mContext.sendBroadcast(new Intent(oldAction));
511                    }
512                    mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
513                    action = UiModeManager.ACTION_ENTER_CAR_MODE;
514                }
515            } else if (isDeskDockState(mDockState)) {
516                if (!isDeskDockState(mLastBroadcastState)) {
517                    if (oldAction != null) {
518                        mContext.sendBroadcast(new Intent(oldAction));
519                    }
520                    mLastBroadcastState = mDockState;
521                    action = UiModeManager.ACTION_ENTER_DESK_MODE;
522                }
523            } else {
524                mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
525                action = oldAction;
526            }
527
528            if (action != null) {
529                if (LOG) {
530                    Slog.v(TAG, String.format(
531                        "updateLocked: preparing broadcast: action=%s enable=0x%08x disable=0x%08x",
532                        action, enableFlags, disableFlags));
533                }
534
535                // Send the ordered broadcast; the result receiver will receive after all
536                // broadcasts have been sent. If any broadcast receiver changes the result
537                // code from the initial value of RESULT_OK, then the result receiver will
538                // not launch the corresponding dock application. This gives apps a chance
539                // to override the behavior and stay in their app even when the device is
540                // placed into a dock.
541                Intent intent = new Intent(action);
542                intent.putExtra("enableFlags", enableFlags);
543                intent.putExtra("disableFlags", disableFlags);
544                mContext.sendOrderedBroadcast(intent, null,
545                        mResultReceiver, null, Activity.RESULT_OK, null, null);
546                // Attempting to make this transition a little more clean, we are going
547                // to hold off on doing a configuration change until we have finished
548                // the broadcast and started the home activity.
549                mHoldingConfiguration = true;
550            } else {
551                Intent homeIntent = null;
552                if (mCarModeEnabled) {
553                    if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
554                        homeIntent = buildHomeIntent(Intent.CATEGORY_CAR_DOCK);
555                    }
556                } else if (isDeskDockState(mDockState)) {
557                    if ((enableFlags&UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
558                        homeIntent = buildHomeIntent(Intent.CATEGORY_DESK_DOCK);
559                    }
560                } else {
561                    if ((disableFlags&UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
562                        homeIntent = buildHomeIntent(Intent.CATEGORY_HOME);
563                    }
564                }
565
566                if (LOG) {
567                    Slog.v(TAG, "updateLocked: null action, mDockState="
568                            + mDockState +", firing homeIntent: " + homeIntent);
569                }
570
571                if (homeIntent != null) {
572                    try {
573                        mContext.startActivity(homeIntent);
574                    } catch (ActivityNotFoundException e) {
575                    }
576                }
577            }
578
579            updateConfigurationLocked(true);
580
581            // keep screen on when charging and in car mode
582            boolean keepScreenOn = mCharging &&
583                    ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
584                     (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
585            if (keepScreenOn != mWakeLock.isHeld()) {
586                if (keepScreenOn) {
587                    mWakeLock.acquire();
588                } else {
589                    mWakeLock.release();
590                }
591            }
592        } finally {
593            Binder.restoreCallingIdentity(ident);
594        }
595    }
596
597    private void adjustStatusBarCarModeLocked() {
598        if (mStatusBarManager == null) {
599            mStatusBarManager = (StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
600        }
601
602        // Fear not: StatusBarManagerService manages a list of requests to disable
603        // features of the status bar; these are ORed together to form the
604        // active disabled list. So if (for example) the device is locked and
605        // the status bar should be totally disabled, the calls below will
606        // have no effect until the device is unlocked.
607        if (mStatusBarManager != null) {
608            mStatusBarManager.disable(mCarModeEnabled
609                ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
610                : StatusBarManager.DISABLE_NONE);
611        }
612
613        if (mNotificationManager == null) {
614            mNotificationManager = (NotificationManager)
615                    mContext.getSystemService(Context.NOTIFICATION_SERVICE);
616        }
617
618        if (mNotificationManager != null) {
619            if (mCarModeEnabled) {
620                Intent carModeOffIntent = new Intent(mContext, DisableCarModeActivity.class);
621
622                Notification n = new Notification();
623                n.icon = R.drawable.stat_notify_car_mode;
624                n.defaults = Notification.DEFAULT_LIGHTS;
625                n.flags = Notification.FLAG_ONGOING_EVENT;
626                n.when = 0;
627                n.setLatestEventInfo(
628                        mContext,
629                        mContext.getString(R.string.car_mode_disable_notification_title),
630                        mContext.getString(R.string.car_mode_disable_notification_message),
631                        PendingIntent.getActivity(mContext, 0, carModeOffIntent, 0));
632                mNotificationManager.notify(0, n);
633            } else {
634                mNotificationManager.cancel(0);
635            }
636        }
637    }
638
639    private final Handler mHandler = new Handler() {
640
641        boolean mPassiveListenerEnabled;
642        boolean mNetworkListenerEnabled;
643        boolean mDidFirstInit;
644        long mLastNetworkRegisterTime = -MIN_LOCATION_UPDATE_MS;
645
646        @Override
647        public void handleMessage(Message msg) {
648            switch (msg.what) {
649                case MSG_UPDATE_TWILIGHT:
650                    synchronized (mLock) {
651                        if (isDoingNightMode() && mLocation != null
652                                && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
653                            updateTwilightLocked();
654                            updateLocked(0, 0);
655                        }
656                    }
657                    break;
658                case MSG_GET_NEW_LOCATION_UPDATE:
659                    if (!mNetworkListenerEnabled) {
660                        // Don't do anything -- we are still trying to get a
661                        // location.
662                        return;
663                    }
664                    if ((mLastNetworkRegisterTime+MIN_LOCATION_UPDATE_MS)
665                            >= SystemClock.elapsedRealtime()) {
666                        // Don't do anything -- it hasn't been long enough
667                        // since we last requested an update.
668                        return;
669                    }
670
671                    // Unregister the current location monitor, so we can
672                    // register a new one for it to get an immediate update.
673                    mNetworkListenerEnabled = false;
674                    mLocationManager.removeUpdates(mEmptyLocationListener);
675
676                    // Fall through to re-register listener.
677                case MSG_ENABLE_LOCATION_UPDATES:
678                    // enable network provider to receive at least location updates for a given
679                    // distance.
680                    boolean networkLocationEnabled;
681                    try {
682                        networkLocationEnabled =
683                            mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
684                    } catch (Exception e) {
685                        // we may get IllegalArgumentException if network location provider
686                        // does not exist or is not yet installed.
687                        networkLocationEnabled = false;
688                    }
689                    if (!mNetworkListenerEnabled && networkLocationEnabled) {
690                        mNetworkListenerEnabled = true;
691                        mLastNetworkRegisterTime = SystemClock.elapsedRealtime();
692                        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
693                                LOCATION_UPDATE_MS, 0, mEmptyLocationListener);
694
695                        if (!mDidFirstInit) {
696                            mDidFirstInit = true;
697                            if (mLocation == null) {
698                                retrieveLocation();
699                            }
700                            synchronized (mLock) {
701                                if (isDoingNightMode() && mLocation != null
702                                        && mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
703                                    updateTwilightLocked();
704                                    updateLocked(0, 0);
705                                }
706                            }
707                        }
708                    }
709                   // enable passive provider to receive updates from location fixes (gps
710                   // and network).
711                   boolean passiveLocationEnabled;
712                    try {
713                        passiveLocationEnabled =
714                            mLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
715                    } catch (Exception e) {
716                        // we may get IllegalArgumentException if passive location provider
717                        // does not exist or is not yet installed.
718                        passiveLocationEnabled = false;
719                    }
720                    if (!mPassiveListenerEnabled && passiveLocationEnabled) {
721                        mPassiveListenerEnabled = true;
722                        mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
723                                0, LOCATION_UPDATE_DISTANCE_METER , mLocationListener);
724                    }
725                    if (!(mNetworkListenerEnabled && mPassiveListenerEnabled)) {
726                        long interval = msg.getData().getLong(KEY_LAST_UPDATE_INTERVAL);
727                        interval *= 1.5;
728                        if (interval == 0) {
729                            interval = LOCATION_UPDATE_ENABLE_INTERVAL_MIN;
730                        } else if (interval > LOCATION_UPDATE_ENABLE_INTERVAL_MAX) {
731                            interval = LOCATION_UPDATE_ENABLE_INTERVAL_MAX;
732                        }
733                        Bundle bundle = new Bundle();
734                        bundle.putLong(KEY_LAST_UPDATE_INTERVAL, interval);
735                        Message newMsg = mHandler.obtainMessage(MSG_ENABLE_LOCATION_UPDATES);
736                        newMsg.setData(bundle);
737                        mHandler.sendMessageDelayed(newMsg, interval);
738                    }
739                    break;
740            }
741        }
742
743        private void retrieveLocation() {
744            Location location = null;
745            final Iterator<String> providers =
746                    mLocationManager.getProviders(new Criteria(), true).iterator();
747            while (providers.hasNext()) {
748                final Location lastKnownLocation =
749                        mLocationManager.getLastKnownLocation(providers.next());
750                // pick the most recent location
751                if (location == null || (lastKnownLocation != null &&
752                        location.getTime() < lastKnownLocation.getTime())) {
753                    location = lastKnownLocation;
754                }
755            }
756            // In the case there is no location available (e.g. GPS fix or network location
757            // is not available yet), the longitude of the location is estimated using the timezone,
758            // latitude and accuracy are set to get a good average.
759            if (location == null) {
760                Time currentTime = new Time();
761                currentTime.set(System.currentTimeMillis());
762                double lngOffset = FACTOR_GMT_OFFSET_LONGITUDE *
763                        (currentTime.gmtoff - (currentTime.isDst > 0 ? 3600 : 0));
764                location = new Location("fake");
765                location.setLongitude(lngOffset);
766                location.setLatitude(0);
767                location.setAccuracy(417000.0f);
768                location.setTime(System.currentTimeMillis());
769            }
770            synchronized (mLock) {
771                mLocation = location;
772            }
773        }
774    };
775
776    void updateTwilightLocked() {
777        if (mLocation == null) {
778            return;
779        }
780        final long currentTime = System.currentTimeMillis();
781        boolean nightMode;
782        // calculate current twilight
783        TwilightCalculator tw = new TwilightCalculator();
784        tw.calculateTwilight(currentTime,
785                mLocation.getLatitude(), mLocation.getLongitude());
786        if (tw.mState == TwilightCalculator.DAY) {
787            nightMode = false;
788        } else {
789            nightMode = true;
790        }
791
792        // schedule next update
793        long nextUpdate = 0;
794        if (tw.mSunrise == -1 || tw.mSunset == -1) {
795            // In the case the day or night never ends the update is scheduled 12 hours later.
796            nextUpdate = currentTime + 12 * DateUtils.HOUR_IN_MILLIS;
797        } else {
798            final int mLastTwilightState = tw.mState;
799            // add some extra time to be on the save side.
800            nextUpdate += DateUtils.MINUTE_IN_MILLIS;
801            if (currentTime > tw.mSunset) {
802                // next update should be on the following day
803                tw.calculateTwilight(currentTime
804                        + DateUtils.DAY_IN_MILLIS, mLocation.getLatitude(),
805                        mLocation.getLongitude());
806            }
807
808            if (mLastTwilightState == TwilightCalculator.NIGHT) {
809                nextUpdate += tw.mSunrise;
810            } else {
811                nextUpdate += tw.mSunset;
812            }
813        }
814
815        Intent updateIntent = new Intent(ACTION_UPDATE_NIGHT_MODE);
816        PendingIntent pendingIntent =
817                PendingIntent.getBroadcast(mContext, 0, updateIntent, 0);
818        mAlarmManager.cancel(pendingIntent);
819        mAlarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdate, pendingIntent);
820
821        mComputedNightMode = nightMode;
822    }
823
824    @Override
825    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
826        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
827                != PackageManager.PERMISSION_GRANTED) {
828
829            pw.println("Permission Denial: can't dump uimode service from from pid="
830                    + Binder.getCallingPid()
831                    + ", uid=" + Binder.getCallingUid());
832            return;
833        }
834
835        synchronized (mLock) {
836            pw.println("Current UI Mode Service state:");
837            pw.print("  mDockState="); pw.print(mDockState);
838                    pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
839            pw.print("  mNightMode="); pw.print(mNightMode);
840                    pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
841                    pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
842            pw.print("  mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
843                    pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
844            pw.print("  mHoldingConfiguration="); pw.print(mHoldingConfiguration);
845                    pw.print(" mSystemReady="); pw.println(mSystemReady);
846            if (mLocation != null) {
847                pw.print("  mLocation="); pw.println(mLocation);
848            }
849        }
850    }
851}
852