summaryrefslogtreecommitdiff
path: root/library/main/src/com/android/setupwizardlib/util/SystemBarHelper.java
blob: 7e3e8859f5b6de2d298c6eb23ecba95e4d20b466 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.setupwizardlib.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowManager;

import androidx.annotation.RequiresPermission;

/**
 * A helper class to manage the system navigation bar and status bar. This will add various
 * systemUiVisibility flags to the given Window or View to make them follow the Setup Wizard style.
 *
 * When the useImmersiveMode intent extra is true, a screen in Setup Wizard should hide the system
 * bars using methods from this class. For Lollipop, {@link #hideSystemBars(android.view.Window)}
 * will completely hide the system navigation bar and change the status bar to transparent, and
 * layout the screen contents (usually the illustration) behind it.
 */
public class SystemBarHelper {

    private static final String TAG = "SystemBarHelper";

    @SuppressLint("InlinedApi")
    private static final int DEFAULT_IMMERSIVE_FLAGS =
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;

    @SuppressLint("InlinedApi")
    private static final int DIALOG_IMMERSIVE_FLAGS =
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

    /**
     * Needs to be equal to View.STATUS_BAR_DISABLE_BACK
     */
    private static final int STATUS_BAR_DISABLE_BACK = 0x00400000;

    /**
     * The maximum number of retries when peeking the decor view. When polling for the decor view,
     * waiting it to be installed, set a maximum number of retries.
     */
    private static final int PEEK_DECOR_VIEW_RETRIES = 3;

    /**
     * Hide the navigation bar for a dialog.
     *
     * <p>This will only take effect in versions Lollipop or above. Otherwise this is a no-op.
     */
    public static void hideSystemBars(final Dialog dialog) {
        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            final Window window = dialog.getWindow();
            temporarilyDisableDialogFocus(window);
            addVisibilityFlag(window, DIALOG_IMMERSIVE_FLAGS);
            addImmersiveFlagsToDecorView(window, DIALOG_IMMERSIVE_FLAGS);

            // Also set the navigation bar and status bar to transparent color. Note that this
            // doesn't work if android.R.boolean.config_enableTranslucentDecor is false.
            window.setNavigationBarColor(0);
            window.setStatusBarColor(0);
        }
    }

    /**
     * Hide the navigation bar, make the color of the status and navigation bars transparent, and
     * specify {@link View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} flag so that the content is laid-out
     * behind the transparent status bar. This is commonly used with
     * {@link android.app.Activity#getWindow()} to make the navigation and status bars follow the
     * Setup Wizard style.
     *
     * <p>This will only take effect in versions Lollipop or above. Otherwise this is a no-op.
     */
    public static void hideSystemBars(final Window window) {
        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            addVisibilityFlag(window, DEFAULT_IMMERSIVE_FLAGS);
            addImmersiveFlagsToDecorView(window, DEFAULT_IMMERSIVE_FLAGS);

            // Also set the navigation bar and status bar to transparent color. Note that this
            // doesn't work if android.R.boolean.config_enableTranslucentDecor is false.
            window.setNavigationBarColor(0);
            window.setStatusBarColor(0);
        }
    }

    /**
     * Revert the actions of hideSystemBars. Note that this will remove the system UI visibility
     * flags regardless of whether it is originally present. You should also manually reset the
     * navigation bar and status bar colors, as this method doesn't know what value to revert it to.
     */
    public static void showSystemBars(final Dialog dialog, final Context context) {
        showSystemBars(dialog.getWindow(), context);
    }

    /**
     * Revert the actions of hideSystemBars. Note that this will remove the system UI visibility
     * flags regardless of whether it is originally present. You should also manually reset the
     * navigation bar and status bar colors, as this method doesn't know what value to revert it to.
     */
    public static void showSystemBars(final Window window, final Context context) {
        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            removeVisibilityFlag(window, DEFAULT_IMMERSIVE_FLAGS);
            removeImmersiveFlagsFromDecorView(window, DEFAULT_IMMERSIVE_FLAGS);

            if (context != null) {
                //noinspection AndroidLintInlinedApi
                final TypedArray typedArray = context.obtainStyledAttributes(new int[]{
                        android.R.attr.statusBarColor, android.R.attr.navigationBarColor});
                final int statusBarColor = typedArray.getColor(0, 0);
                final int navigationBarColor = typedArray.getColor(1, 0);
                window.setStatusBarColor(statusBarColor);
                window.setNavigationBarColor(navigationBarColor);
                typedArray.recycle();
            }
        }
    }

    /**
     * Convenience method to add a visibility flag in addition to the existing ones.
     */
    public static void addVisibilityFlag(final View view, final int flag) {
        if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
            final int vis = view.getSystemUiVisibility();
            view.setSystemUiVisibility(vis | flag);
        }
    }

    /**
     * Convenience method to add a visibility flag in addition to the existing ones.
     */
    public static void addVisibilityFlag(final Window window, final int flag) {
        if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
            WindowManager.LayoutParams attrs = window.getAttributes();
            attrs.systemUiVisibility |= flag;
            window.setAttributes(attrs);
        }
    }

    /**
     * Convenience method to remove a visibility flag from the view, leaving other flags that are
     * not specified intact.
     */
    public static void removeVisibilityFlag(final View view, final int flag) {
        if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
            final int vis = view.getSystemUiVisibility();
            view.setSystemUiVisibility(vis & ~flag);
        }
    }

    /**
     * Convenience method to remove a visibility flag from the window, leaving other flags that are
     * not specified intact.
     */
    public static void removeVisibilityFlag(final Window window, final int flag) {
        if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
            WindowManager.LayoutParams attrs = window.getAttributes();
            attrs.systemUiVisibility &= ~flag;
            window.setAttributes(attrs);
        }
    }

    /**
     * Sets whether the back button on the software navigation bar is visible. This only works if
     * you have the STATUS_BAR permission. Otherwise framework will filter out this flag and this
     * method call will not have any effect.
     *
     * <p>IMPORTANT: Do not assume that users have no way to go back when the back button is hidden.
     * Many devices have physical back buttons, and accessibility services like TalkBack may have
     * gestures mapped to back. Please use onBackPressed, onKeyDown, or other similar ways to
     * make sure back button events are still handled (or ignored) properly.
     */
    @RequiresPermission("android.permission.STATUS_BAR")
    public static void setBackButtonVisible(final Window window, final boolean visible) {
        if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
            if (visible) {
                removeVisibilityFlag(window, STATUS_BAR_DISABLE_BACK);
                removeImmersiveFlagsFromDecorView(window, STATUS_BAR_DISABLE_BACK);
            } else {
                addVisibilityFlag(window, STATUS_BAR_DISABLE_BACK);
                addImmersiveFlagsToDecorView(window, STATUS_BAR_DISABLE_BACK);
            }
        }
    }

    /**
     * Set a view to be resized when the keyboard is shown. This will set the bottom margin of the
     * view to be immediately above the keyboard, and assumes that the view sits immediately above
     * the navigation bar.
     *
     * <p>Note that you must set {@link android.R.attr#windowSoftInputMode} to {@code adjustResize}
     * for this class to work. Otherwise window insets are not dispatched and this method will have
     * no effect.
     *
     * <p>This will only take effect in versions Lollipop or above. Otherwise this is a no-op.
     *
     * @param view The view to be resized when the keyboard is shown.
     */
    public static void setImeInsetView(final View view) {
        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            view.setOnApplyWindowInsetsListener(new WindowInsetsListener());
        }
    }

    /**
     * Add the specified immersive flags to the decor view of the window, because
     * {@link View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} only takes effect when it is added to a view
     * instead of the window.
     */
    @TargetApi(VERSION_CODES.HONEYCOMB)
    private static void addImmersiveFlagsToDecorView(final Window window, final int vis) {
        getDecorView(window, new OnDecorViewInstalledListener() {
            @Override
            public void onDecorViewInstalled(View decorView) {
                addVisibilityFlag(decorView, vis);
            }
        });
    }

    @TargetApi(VERSION_CODES.HONEYCOMB)
    private static void removeImmersiveFlagsFromDecorView(final Window window, final int vis) {
        getDecorView(window, new OnDecorViewInstalledListener() {
            @Override
            public void onDecorViewInstalled(View decorView) {
                removeVisibilityFlag(decorView, vis);
            }
        });
    }

    private static void getDecorView(Window window, OnDecorViewInstalledListener callback) {
        new DecorViewFinder().getDecorView(window, callback, PEEK_DECOR_VIEW_RETRIES);
    }

    private static class DecorViewFinder {

        private final Handler mHandler = new Handler();
        private Window mWindow;
        private int mRetries;
        private OnDecorViewInstalledListener mCallback;

        private Runnable mCheckDecorViewRunnable = new Runnable() {
            @Override
            public void run() {
                // Use peekDecorView instead of getDecorView so that clients can still set window
                // features after calling this method.
                final View decorView = mWindow.peekDecorView();
                if (decorView != null) {
                    mCallback.onDecorViewInstalled(decorView);
                } else {
                    mRetries--;
                    if (mRetries >= 0) {
                        // If the decor view is not installed yet, try again in the next loop.
                        mHandler.post(mCheckDecorViewRunnable);
                    } else {
                        Log.w(TAG, "Cannot get decor view of window: " + mWindow);
                    }
                }
            }
        };

        public void getDecorView(Window window, OnDecorViewInstalledListener callback,
                int retries) {
            mWindow = window;
            mRetries = retries;
            mCallback = callback;
            mCheckDecorViewRunnable.run();
        }
    }

    private interface OnDecorViewInstalledListener {

        void onDecorViewInstalled(View decorView);
    }

    /**
     * Apply a hack to temporarily set the window to not focusable, so that the navigation bar
     * will not show up during the transition.
     */
    private static void temporarilyDisableDialogFocus(final Window window) {
        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        // Add the SOFT_INPUT_IS_FORWARD_NAVIGATION_FLAG. This is normally done by the system when
        // FLAG_NOT_FOCUSABLE is not set. Setting this flag allows IME to be shown automatically
        // if the dialog has editable text fields.
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION);
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
            }
        });
    }

    @TargetApi(VERSION_CODES.LOLLIPOP)
    private static class WindowInsetsListener implements View.OnApplyWindowInsetsListener {
        private int mBottomOffset;
        private boolean mHasCalculatedBottomOffset = false;

        @Override
        public WindowInsets onApplyWindowInsets(View view, WindowInsets insets) {
            if (!mHasCalculatedBottomOffset) {
                mBottomOffset = getBottomDistance(view);
                mHasCalculatedBottomOffset = true;
            }

            int bottomInset = insets.getSystemWindowInsetBottom();

            final int bottomMargin = Math.max(
                    insets.getSystemWindowInsetBottom() - mBottomOffset, 0);

            final ViewGroup.MarginLayoutParams lp =
                    (ViewGroup.MarginLayoutParams) view.getLayoutParams();
            // Check that we have enough space to apply the bottom margins before applying it.
            // Otherwise the framework may think that the view is empty and exclude it from layout.
            if (bottomMargin < lp.bottomMargin + view.getHeight()) {
                lp.setMargins(lp.leftMargin, lp.topMargin, lp.rightMargin, bottomMargin);
                view.setLayoutParams(lp);
                bottomInset = 0;
            }


            return insets.replaceSystemWindowInsets(
                    insets.getSystemWindowInsetLeft(),
                    insets.getSystemWindowInsetTop(),
                    insets.getSystemWindowInsetRight(),
                    bottomInset
            );
        }
    }

    private static int getBottomDistance(View view) {
        int[] coords = new int[2];
        view.getLocationInWindow(coords);
        return view.getRootView().getHeight() - coords[1] - view.getHeight();
    }
}