NavigationBarFragment.java revision aa573e9e8632552d1fa8bdd6b0ee408ff9a93a6b
1/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. You may obtain a copy of the License at
6 *
7 *      http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11 * KIND, either express or implied. See the License for the specific language governing
12 * permissions and limitations under the License.
13 */
14
15package com.android.systemui.statusbar.phone;
16
17import static android.app.StatusBarManager.NAVIGATION_HINT_BACK_ALT;
18import static android.app.StatusBarManager.NAVIGATION_HINT_IME_SHOWN;
19import static android.app.StatusBarManager.WINDOW_STATE_SHOWING;
20import static android.app.StatusBarManager.windowStateToString;
21
22import static com.android.systemui.statusbar.phone.BarTransitions.MODE_SEMI_TRANSPARENT;
23import static com.android.systemui.statusbar.phone.StatusBar.DEBUG_WINDOW_STATE;
24import static com.android.systemui.statusbar.phone.StatusBar.dumpBarTransitions;
25
26import android.accessibilityservice.AccessibilityServiceInfo;
27import android.annotation.Nullable;
28import android.app.ActivityManager;
29import android.app.ActivityManagerNative;
30import android.app.Fragment;
31import android.app.IActivityManager;
32import android.app.StatusBarManager;
33import android.content.BroadcastReceiver;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.res.Configuration;
38import android.graphics.PixelFormat;
39import android.graphics.Rect;
40import android.inputmethodservice.InputMethodService;
41import android.os.Binder;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Message;
46import android.os.PowerManager;
47import android.os.RemoteException;
48import android.os.UserHandle;
49import android.support.annotation.VisibleForTesting;
50import android.telecom.TelecomManager;
51import android.text.TextUtils;
52import android.util.Log;
53import android.view.IRotationWatcher.Stub;
54import android.view.KeyEvent;
55import android.view.LayoutInflater;
56import android.view.MotionEvent;
57import android.view.View;
58import android.view.ViewGroup;
59import android.view.WindowManager;
60import android.view.WindowManager.LayoutParams;
61import android.view.WindowManagerGlobal;
62import android.view.accessibility.AccessibilityEvent;
63import android.view.accessibility.AccessibilityManager;
64
65import com.android.internal.logging.MetricsLogger;
66import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
67import com.android.keyguard.LatencyTracker;
68import com.android.systemui.Dependency;
69import com.android.systemui.R;
70import com.android.systemui.SysUiServiceProvider;
71import com.android.systemui.assist.AssistManager;
72import com.android.systemui.fragments.FragmentHostManager;
73import com.android.systemui.fragments.FragmentHostManager.FragmentListener;
74import com.android.systemui.recents.Recents;
75import com.android.systemui.stackdivider.Divider;
76import com.android.systemui.statusbar.CommandQueue;
77import com.android.systemui.statusbar.CommandQueue.Callbacks;
78import com.android.systemui.statusbar.policy.KeyButtonView;
79import com.android.systemui.statusbar.stack.StackStateAnimator;
80
81import java.io.FileDescriptor;
82import java.io.PrintWriter;
83import java.util.List;
84import java.util.Locale;
85
86/**
87 * Fragment containing the NavigationBarFragment. Contains logic for what happens
88 * on clicks and view states of the nav bar.
89 */
90public class NavigationBarFragment extends Fragment implements Callbacks {
91
92    private static final String TAG = "NavigationBar";
93    private static final boolean DEBUG = false;
94    private static final String EXTRA_DISABLE_STATE = "disabled_state";
95
96    /** Allow some time inbetween the long press for back and recents. */
97    private static final int LOCK_TO_APP_GESTURE_TOLERENCE = 200;
98
99    protected NavigationBarView mNavigationBarView = null;
100    protected AssistManager mAssistManager;
101
102    private int mNavigationBarWindowState = WINDOW_STATE_SHOWING;
103
104    private int mNavigationIconHints = 0;
105    private int mNavigationBarMode;
106    private AccessibilityManager mAccessibilityManager;
107
108    private int mDisabledFlags1;
109    private StatusBar mStatusBar;
110    private Recents mRecents;
111    private Divider mDivider;
112    private WindowManager mWindowManager;
113    private CommandQueue mCommandQueue;
114    private long mLastLockToAppLongPress;
115
116    private Locale mLocale;
117    private int mLayoutDirection;
118
119    private int mSystemUiVisibility;
120    private LightBarController mLightBarController;
121
122    public boolean mHomeBlockedThisTouch;
123
124    // ----- Fragment Lifecycle Callbacks -----
125
126    @Override
127    public void onCreate(@Nullable Bundle savedInstanceState) {
128        super.onCreate(savedInstanceState);
129        mCommandQueue = SysUiServiceProvider.getComponent(getContext(), CommandQueue.class);
130        mCommandQueue.addCallbacks(this);
131        mStatusBar = SysUiServiceProvider.getComponent(getContext(), StatusBar.class);
132        mRecents = SysUiServiceProvider.getComponent(getContext(), Recents.class);
133        mDivider = SysUiServiceProvider.getComponent(getContext(), Divider.class);
134        mWindowManager = getContext().getSystemService(WindowManager.class);
135        mAccessibilityManager = getContext().getSystemService(AccessibilityManager.class);
136        mAccessibilityManager.addAccessibilityServicesStateChangeListener(
137                this::updateAccessibilityServicesState);
138        if (savedInstanceState != null) {
139            mDisabledFlags1 = savedInstanceState.getInt(EXTRA_DISABLE_STATE, 0);
140        }
141        mAssistManager = Dependency.get(AssistManager.class);
142
143        try {
144            WindowManagerGlobal.getWindowManagerService()
145                    .watchRotation(mRotationWatcher);
146        } catch (RemoteException e) {
147            throw e.rethrowFromSystemServer();
148        }
149    }
150
151    @Override
152    public void onDestroy() {
153        super.onDestroy();
154        mCommandQueue.removeCallbacks(this);
155        mAccessibilityManager.removeAccessibilityServicesStateChangeListener(
156                this::updateAccessibilityServicesState);
157        try {
158            WindowManagerGlobal.getWindowManagerService()
159                    .removeRotationWatcher(mRotationWatcher);
160        } catch (RemoteException e) {
161            throw e.rethrowFromSystemServer();
162        }
163    }
164
165    @Override
166    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
167            Bundle savedInstanceState) {
168        return inflater.inflate(R.layout.navigation_bar, container, false);
169    }
170
171    @Override
172    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
173        super.onViewCreated(view, savedInstanceState);
174        mNavigationBarView = (NavigationBarView) view;
175
176        mNavigationBarView.setDisabledFlags(mDisabledFlags1);
177        mNavigationBarView.setComponents(mRecents, mDivider);
178        mNavigationBarView.setOnVerticalChangedListener(this::onVerticalChanged);
179        mNavigationBarView.setOnTouchListener(this::onNavigationTouch);
180        if (savedInstanceState != null) {
181            mNavigationBarView.getLightTransitionsController().restoreState(savedInstanceState);
182        }
183
184        prepareNavigationBarView();
185        checkNavBarModes();
186
187        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
188        filter.addAction(Intent.ACTION_SCREEN_ON);
189        getContext().registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
190        PowerManager pm = getContext().getSystemService(PowerManager.class);
191        notifyNavigationBarScreenOn(pm.isScreenOn());
192    }
193
194    @Override
195    public void onDestroyView() {
196        super.onDestroyView();
197        mNavigationBarView.getLightTransitionsController().destroy(getContext());
198        getContext().unregisterReceiver(mBroadcastReceiver);
199    }
200
201    @Override
202    public void onSaveInstanceState(Bundle outState) {
203        super.onSaveInstanceState(outState);
204        outState.putInt(EXTRA_DISABLE_STATE, mDisabledFlags1);
205        if (mNavigationBarView != null) {
206            mNavigationBarView.getLightTransitionsController().saveState(outState);
207        }
208    }
209
210    @Override
211    public void onConfigurationChanged(Configuration newConfig) {
212        super.onConfigurationChanged(newConfig);
213        final Locale locale = getContext().getResources().getConfiguration().locale;
214        final int ld = TextUtils.getLayoutDirectionFromLocale(locale);
215        if (!locale.equals(mLocale) || ld != mLayoutDirection) {
216            if (DEBUG) {
217                Log.v(TAG, String.format(
218                        "config changed locale/LD: %s (%d) -> %s (%d)", mLocale, mLayoutDirection,
219                        locale, ld));
220            }
221            mLocale = locale;
222            mLayoutDirection = ld;
223            refreshLayout(ld);
224        }
225        repositionNavigationBar();
226    }
227
228    @Override
229    public void dump(String prefix, FileDescriptor fd, PrintWriter pw, String[] args) {
230        if (mNavigationBarView != null) {
231            pw.print("  mNavigationBarWindowState=");
232            pw.println(windowStateToString(mNavigationBarWindowState));
233            pw.print("  mNavigationBarMode=");
234            pw.println(BarTransitions.modeToString(mNavigationBarMode));
235            dumpBarTransitions(pw, "mNavigationBarView", mNavigationBarView.getBarTransitions());
236        }
237
238        pw.print("  mNavigationBarView=");
239        if (mNavigationBarView == null) {
240            pw.println("null");
241        } else {
242            mNavigationBarView.dump(fd, pw, args);
243        }
244    }
245
246    // ----- CommandQueue Callbacks -----
247
248    @Override
249    public void setImeWindowStatus(IBinder token, int vis, int backDisposition,
250            boolean showImeSwitcher) {
251        boolean imeShown = (vis & InputMethodService.IME_VISIBLE) != 0;
252        int hints = mNavigationIconHints;
253        if ((backDisposition == InputMethodService.BACK_DISPOSITION_WILL_DISMISS) || imeShown) {
254            hints |= NAVIGATION_HINT_BACK_ALT;
255        } else {
256            hints &= ~NAVIGATION_HINT_BACK_ALT;
257        }
258        if (showImeSwitcher) {
259            hints |= NAVIGATION_HINT_IME_SHOWN;
260        } else {
261            hints &= ~NAVIGATION_HINT_IME_SHOWN;
262        }
263        if (hints == mNavigationIconHints) return;
264
265        mNavigationIconHints = hints;
266
267        if (mNavigationBarView != null) {
268            mNavigationBarView.setNavigationIconHints(hints);
269        }
270        mStatusBar.checkBarModes();
271    }
272
273    @Override
274    public void topAppWindowChanged(boolean showMenu) {
275        if (mNavigationBarView != null) {
276            mNavigationBarView.setMenuVisibility(showMenu);
277        }
278    }
279
280    @Override
281    public void setWindowState(int window, int state) {
282        if (mNavigationBarView != null
283                && window == StatusBarManager.WINDOW_NAVIGATION_BAR
284                && mNavigationBarWindowState != state) {
285            mNavigationBarWindowState = state;
286            if (DEBUG_WINDOW_STATE) Log.d(TAG, "Navigation bar " + windowStateToString(state));
287        }
288    }
289
290    // Injected from StatusBar at creation.
291    public void setCurrentSysuiVisibility(int systemUiVisibility) {
292        mSystemUiVisibility = systemUiVisibility;
293        mNavigationBarMode = mStatusBar.computeBarMode(0, mSystemUiVisibility,
294                View.NAVIGATION_BAR_TRANSIENT, View.NAVIGATION_BAR_TRANSLUCENT,
295                View.NAVIGATION_BAR_TRANSPARENT);
296        checkNavBarModes();
297        mStatusBar.touchAutoHide();
298        mLightBarController.onNavigationVisibilityChanged(mSystemUiVisibility, 0 /* mask */,
299                true /* nbModeChanged */, mNavigationBarMode);
300    }
301
302    @Override
303    public void setSystemUiVisibility(int vis, int fullscreenStackVis, int dockedStackVis,
304            int mask, Rect fullscreenStackBounds, Rect dockedStackBounds) {
305        final int oldVal = mSystemUiVisibility;
306        final int newVal = (oldVal & ~mask) | (vis & mask);
307        final int diff = newVal ^ oldVal;
308        boolean nbModeChanged = false;
309        if (diff != 0) {
310            mSystemUiVisibility = newVal;
311
312            // update navigation bar mode
313            final int nbMode = getView() == null
314                    ? -1 : mStatusBar.computeBarMode(oldVal, newVal,
315                    View.NAVIGATION_BAR_TRANSIENT, View.NAVIGATION_BAR_TRANSLUCENT,
316                    View.NAVIGATION_BAR_TRANSPARENT);
317            nbModeChanged = nbMode != -1;
318            if (nbModeChanged) {
319                if (mNavigationBarMode != nbMode) {
320                    mNavigationBarMode = nbMode;
321                    checkNavBarModes();
322                }
323                mStatusBar.touchAutoHide();
324            }
325        }
326
327        mLightBarController.onNavigationVisibilityChanged(vis, mask, nbModeChanged,
328                mNavigationBarMode);
329    }
330
331    @Override
332    public void disable(int state1, int state2, boolean animate) {
333        // All navigation bar flags are in state1.
334        int masked = state1 & (StatusBarManager.DISABLE_HOME
335                | StatusBarManager.DISABLE_RECENT
336                | StatusBarManager.DISABLE_BACK
337                | StatusBarManager.DISABLE_SEARCH);
338        if (masked != mDisabledFlags1) {
339            mDisabledFlags1 = masked;
340            if (mNavigationBarView != null) mNavigationBarView.setDisabledFlags(state1);
341        }
342    }
343
344    // ----- Internal stuffz -----
345
346    private void refreshLayout(int layoutDirection) {
347        if (mNavigationBarView != null) {
348            mNavigationBarView.setLayoutDirection(layoutDirection);
349        }
350    }
351
352    private boolean shouldDisableNavbarGestures() {
353        return !mStatusBar.isDeviceProvisioned()
354                || (mDisabledFlags1 & StatusBarManager.DISABLE_SEARCH) != 0;
355    }
356
357    private void repositionNavigationBar() {
358        if (mNavigationBarView == null || !mNavigationBarView.isAttachedToWindow()) return;
359
360        prepareNavigationBarView();
361
362        mWindowManager.updateViewLayout((View) mNavigationBarView.getParent(),
363                ((View) mNavigationBarView.getParent()).getLayoutParams());
364    }
365
366    private void notifyNavigationBarScreenOn(boolean screenOn) {
367        mNavigationBarView.notifyScreenOn(screenOn);
368    }
369
370    private void prepareNavigationBarView() {
371        mNavigationBarView.reorient();
372
373        ButtonDispatcher recentsButton = mNavigationBarView.getRecentsButton();
374        recentsButton.setOnClickListener(this::onRecentsClick);
375        recentsButton.setOnTouchListener(this::onRecentsTouch);
376        recentsButton.setLongClickable(true);
377        recentsButton.setOnLongClickListener(this::onLongPressBackRecents);
378
379        ButtonDispatcher backButton = mNavigationBarView.getBackButton();
380        backButton.setLongClickable(true);
381        backButton.setOnLongClickListener(this::onLongPressBackRecents);
382
383        ButtonDispatcher homeButton = mNavigationBarView.getHomeButton();
384        homeButton.setOnTouchListener(this::onHomeTouch);
385        homeButton.setOnLongClickListener(this::onHomeLongClick);
386
387        ButtonDispatcher accessibilityButton = mNavigationBarView.getAccessibilityButton();
388        accessibilityButton.setOnClickListener(this::onAccessibilityClick);
389        accessibilityButton.setOnLongClickListener(this::onAccessibilityLongClick);
390    }
391
392    private boolean onHomeTouch(View v, MotionEvent event) {
393        if (mHomeBlockedThisTouch && event.getActionMasked() != MotionEvent.ACTION_DOWN) {
394            return true;
395        }
396        // If an incoming call is ringing, HOME is totally disabled.
397        // (The user is already on the InCallUI at this point,
398        // and his ONLY options are to answer or reject the call.)
399        switch (event.getAction()) {
400            case MotionEvent.ACTION_DOWN:
401                mHomeBlockedThisTouch = false;
402                TelecomManager telecomManager =
403                        getContext().getSystemService(TelecomManager.class);
404                if (telecomManager != null && telecomManager.isRinging()) {
405                    if (mStatusBar.isKeyguardShowing()) {
406                        Log.i(TAG, "Ignoring HOME; there's a ringing incoming call. " +
407                                "No heads up");
408                        mHomeBlockedThisTouch = true;
409                        return true;
410                    }
411                }
412                break;
413            case MotionEvent.ACTION_UP:
414            case MotionEvent.ACTION_CANCEL:
415                mStatusBar.awakenDreams();
416                break;
417        }
418        return false;
419    }
420
421    private void onVerticalChanged(boolean isVertical) {
422        mStatusBar.setQsScrimEnabled(!isVertical);
423    }
424
425    private boolean onNavigationTouch(View v, MotionEvent event) {
426        mStatusBar.checkUserAutohide(v, event);
427        return false;
428    }
429
430    @VisibleForTesting
431    boolean onHomeLongClick(View v) {
432        if (shouldDisableNavbarGestures()) {
433            return false;
434        }
435        MetricsLogger.action(getContext(), MetricsEvent.ACTION_ASSIST_LONG_PRESS);
436        mAssistManager.startAssist(new Bundle() /* args */);
437        mStatusBar.awakenDreams();
438        if (mNavigationBarView != null) {
439            mNavigationBarView.abortCurrentGesture();
440        }
441        return true;
442    }
443
444    // additional optimization when we have software system buttons - start loading the recent
445    // tasks on touch down
446    private boolean onRecentsTouch(View v, MotionEvent event) {
447        int action = event.getAction() & MotionEvent.ACTION_MASK;
448        if (action == MotionEvent.ACTION_DOWN) {
449            mCommandQueue.preloadRecentApps();
450        } else if (action == MotionEvent.ACTION_CANCEL) {
451            mCommandQueue.cancelPreloadRecentApps();
452        } else if (action == MotionEvent.ACTION_UP) {
453            if (!v.isPressed()) {
454                mCommandQueue.cancelPreloadRecentApps();
455            }
456        }
457        return false;
458    }
459
460    private void onRecentsClick(View v) {
461        if (LatencyTracker.isEnabled(getContext())) {
462            LatencyTracker.getInstance(getContext()).onActionStart(
463                    LatencyTracker.ACTION_TOGGLE_RECENTS);
464        }
465        mStatusBar.awakenDreams();
466        mCommandQueue.toggleRecentApps();
467    }
468
469    /**
470     * This handles long-press of both back and recents.  They are
471     * handled together to capture them both being long-pressed
472     * at the same time to exit screen pinning (lock task).
473     *
474     * When accessibility mode is on, only a long-press from recents
475     * is required to exit.
476     *
477     * In all other circumstances we try to pass through long-press events
478     * for Back, so that apps can still use it.  Which can be from two things.
479     * 1) Not currently in screen pinning (lock task).
480     * 2) Back is long-pressed without recents.
481     */
482    private boolean onLongPressBackRecents(View v) {
483        try {
484            boolean sendBackLongPress = false;
485            IActivityManager activityManager = ActivityManagerNative.getDefault();
486            boolean touchExplorationEnabled = mAccessibilityManager.isTouchExplorationEnabled();
487            boolean inLockTaskMode = activityManager.isInLockTaskMode();
488            if (inLockTaskMode && !touchExplorationEnabled) {
489                long time = System.currentTimeMillis();
490                // If we recently long-pressed the other button then they were
491                // long-pressed 'together'
492                if ((time - mLastLockToAppLongPress) < LOCK_TO_APP_GESTURE_TOLERENCE) {
493                    activityManager.stopLockTaskMode();
494                    // When exiting refresh disabled flags.
495                    mNavigationBarView.setDisabledFlags(mDisabledFlags1, true);
496                    return true;
497                } else if ((v.getId() == R.id.back)
498                        && !mNavigationBarView.getRecentsButton().getCurrentView().isPressed()) {
499                    // If we aren't pressing recents right now then they presses
500                    // won't be together, so send the standard long-press action.
501                    sendBackLongPress = true;
502                }
503                mLastLockToAppLongPress = time;
504            } else {
505                // If this is back still need to handle sending the long-press event.
506                if (v.getId() == R.id.back) {
507                    sendBackLongPress = true;
508                } else if (touchExplorationEnabled && inLockTaskMode) {
509                    // When in accessibility mode a long press that is recents (not back)
510                    // should stop lock task.
511                    activityManager.stopLockTaskMode();
512                    // When exiting refresh disabled flags.
513                    mNavigationBarView.setDisabledFlags(mDisabledFlags1, true);
514                    return true;
515                } else if (v.getId() == R.id.recent_apps) {
516                    return onLongPressRecents();
517                }
518            }
519            if (sendBackLongPress) {
520                KeyButtonView keyButtonView = (KeyButtonView) v;
521                keyButtonView.sendEvent(KeyEvent.ACTION_DOWN, KeyEvent.FLAG_LONG_PRESS);
522                keyButtonView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
523                return true;
524            }
525        } catch (RemoteException e) {
526            Log.d(TAG, "Unable to reach activity manager", e);
527        }
528        return false;
529    }
530
531    private boolean onLongPressRecents() {
532        if (mRecents == null || !ActivityManager.supportsMultiWindow()
533                || !mDivider.getView().getSnapAlgorithm().isSplitScreenFeasible()) {
534            return false;
535        }
536
537        return mStatusBar.toggleSplitScreenMode(MetricsEvent.ACTION_WINDOW_DOCK_LONGPRESS,
538                MetricsEvent.ACTION_WINDOW_UNDOCK_LONGPRESS);
539    }
540
541    private void onAccessibilityClick(View v) {
542        mAccessibilityManager.notifyAccessibilityButtonClicked();
543    }
544
545    private boolean onAccessibilityLongClick(View v) {
546        // TODO(b/34720082): Target service selection via long click
547        android.widget.Toast.makeText(getContext(), "Service selection coming soon...",
548                android.widget.Toast.LENGTH_LONG).show();
549        return true;
550    }
551
552    private void updateAccessibilityServicesState() {
553        final List<AccessibilityServiceInfo> services =
554                mAccessibilityManager.getEnabledAccessibilityServiceList(
555                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
556        int requestingServices = 0;
557        for (int i = services.size() - 1; i >= 0; --i) {
558            AccessibilityServiceInfo info = services.get(i);
559            if ((info.flags & AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON) != 0) {
560                requestingServices++;
561            }
562        }
563
564        final boolean showAccessibilityButton = requestingServices >= 1;
565        final boolean targetSelection = requestingServices >= 2;
566        mNavigationBarView.setAccessibilityButtonState(showAccessibilityButton, targetSelection);
567    }
568
569    // ----- Methods that StatusBar talks to (should be minimized) -----
570
571    public void setLightBarController(LightBarController lightBarController) {
572        mLightBarController = lightBarController;
573        mLightBarController.setNavigationBar(mNavigationBarView.getLightTransitionsController());
574    }
575
576    public boolean isSemiTransparent() {
577        return mNavigationBarMode == MODE_SEMI_TRANSPARENT;
578    }
579
580    public void onKeyguardOccludedChanged(boolean keyguardOccluded) {
581        mNavigationBarView.onKeyguardOccludedChanged(keyguardOccluded);
582    }
583
584    public void disableAnimationsDuringHide(long delay) {
585        mNavigationBarView.setLayoutTransitionsEnabled(false);
586        mNavigationBarView.postDelayed(() -> mNavigationBarView.setLayoutTransitionsEnabled(true),
587                delay + StackStateAnimator.ANIMATION_DURATION_GO_TO_FULL_SHADE);
588    }
589
590    public BarTransitions getBarTransitions() {
591        return mNavigationBarView.getBarTransitions();
592    }
593
594    public void checkNavBarModes() {
595        mStatusBar.checkBarMode(mNavigationBarMode,
596                mNavigationBarWindowState, mNavigationBarView.getBarTransitions());
597    }
598
599    public void finishBarAnimations() {
600        mNavigationBarView.getBarTransitions().finishAnimations();
601    }
602
603    private final Stub mRotationWatcher = new Stub() {
604        @Override
605        public void onRotationChanged(int rotation) throws RemoteException {
606            // We need this to be scheduled as early as possible to beat the redrawing of
607            // window in response to the orientation change.
608            Handler h = getView().getHandler();
609            Message msg = Message.obtain(h, () -> {
610                if (mNavigationBarView != null
611                        && mNavigationBarView.needsReorient(rotation)) {
612                    repositionNavigationBar();
613                }
614            });
615            msg.setAsynchronous(true);
616            h.sendMessageAtFrontOfQueue(msg);
617        }
618    };
619
620    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
621        @Override
622        public void onReceive(Context context, Intent intent) {
623            String action = intent.getAction();
624            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
625                notifyNavigationBarScreenOn(false);
626            } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
627                notifyNavigationBarScreenOn(true);
628            }
629        }
630    };
631
632    public static View create(Context context, FragmentListener listener) {
633        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
634                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
635                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
636                WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
637                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
638                        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
639                        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
640                        | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
641                        | WindowManager.LayoutParams.FLAG_SLIPPERY,
642                PixelFormat.TRANSLUCENT);
643        lp.token = new Binder();
644        // this will allow the navbar to run in an overlay on devices that support this
645        if (ActivityManager.isHighEndGfx()) {
646            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
647        }
648        lp.setTitle("NavigationBar");
649        lp.windowAnimations = 0;
650
651        View navigationBarView = LayoutInflater.from(context).inflate(
652                R.layout.navigation_bar_window, null);
653
654        if (DEBUG) Log.v(TAG, "addNavigationBar: about to add " + navigationBarView);
655        if (navigationBarView == null) return null;
656
657        context.getSystemService(WindowManager.class).addView(navigationBarView, lp);
658        FragmentHostManager fragmentHost = FragmentHostManager.get(navigationBarView);
659        NavigationBarFragment fragment = new NavigationBarFragment();
660        fragmentHost.getFragmentManager().beginTransaction()
661                .replace(R.id.navigation_bar_frame, fragment, TAG)
662                .commit();
663        fragmentHost.addTagListener(TAG, listener);
664        return navigationBarView;
665    }
666}
667