summaryrefslogtreecommitdiffstats
path: root/src/com/android/bips/P2pPermissionManager.java
blob: 027d764488f5042cff726768ecb827f0c2009abe (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
/*
 * Copyright (C) 2019 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.bips;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Icon;
import android.location.LocationManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import com.android.bips.ui.AddPrintersActivity;
import com.android.bips.ui.AddPrintersFragment;

/**
 * Manage Wi-Fi Direct permission requirements and state.
 */
public class P2pPermissionManager {
    private static final String TAG = P2pPermissionManager.class.getCanonicalName();
    private static final boolean DEBUG = false;

    private static final String CHANNEL_ID_CONNECTIONS = "connections";
    public static final int REQUEST_P2P_PERMISSION_CODE = 1000;
    public static final int REQUEST_LOCATION_ENABLE = 1001;

    private static final String STATE_KEY = "state";

    private static final P2pPermissionRequest sFinishedRequest = () -> { };

    private final Context mContext;
    private final SharedPreferences mPrefs;
    private final NotificationManager mNotificationManager;

    public P2pPermissionManager(Context context) {
        mContext = context;
        mPrefs = mContext.getSharedPreferences(TAG, 0);
        mNotificationManager = mContext.getSystemService(NotificationManager.class);
    }

    /**
     * Reset any temporary modes.
     */
    public void reset() {
        if (getState() == State.TEMPORARILY_DISABLED) {
            setState(State.DENIED);
        }
    }

    /**
     * Update the current P2P permissions request state.
     */
    public void setState(State state) {
        if (DEBUG) Log.d(TAG, "State from " + mPrefs.getString(STATE_KEY, "?") + " to " + state);
        mPrefs.edit().putString(STATE_KEY, state.name()).apply();
    }

    /**
     * Return true if P2P features are enabled.
     */
    public boolean isP2pEnabled() {
        return getState() == State.ALLOWED;
    }

    /**
     * The user has made a permissions-related choice.
     */
    public void applyPermissionChange(boolean permanent) {
        closeNotification();
        if (hasP2pPermission()) {
            setState(State.ALLOWED);
        } else if (getState() != State.DISABLED) {
            if (permanent) {
                setState(State.DISABLED);
            } else {
                // Inform the user and don't try again for the rest of this session.
                setState(State.TEMPORARILY_DISABLED);
                Toast.makeText(mContext, R.string.wifi_direct_permission_rationale,
                        Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * Return true if the user has granted P2P-related permission.
     */
    private boolean hasP2pPermission() {
        return mContext.checkSelfPermission(ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * Request P2P permission from the user, until the user makes a selection or the returned
     * {@link P2pPermissionRequest} is closed.
     *
     * Note: if requested on behalf of an Activity, the Activity MUST call
     * {@link P2pPermissionManager#applyPermissionChange(boolean)} whenever
     * {@link Activity#onRequestPermissionsResult(int, String[], int[])} is called with code
     * {@link P2pPermissionManager#REQUEST_P2P_PERMISSION_CODE}.
     */
    public P2pPermissionRequest request(boolean explain, P2pPermissionListener listener) {
        // Check current permission level
        State state = getState();

        if (DEBUG) Log.d(TAG, "request() state=" + state);

        if (state.isTerminal()) {
            listener.onP2pPermissionComplete(state == State.ALLOWED);
            // Nothing to close because no listener registered.
            return sFinishedRequest;
        }

        SharedPreferences.OnSharedPreferenceChangeListener preferenceListener =
                listenForPreferenceChanges(listener);

        if (mContext instanceof Activity) {
            Activity activity = (Activity) mContext;
            if (!isLocationEnabled()) {
                requestLocation(activity);
            } else if (!hasP2pPermission()) {
                if (explain && activity.shouldShowRequestPermissionRationale(
                        ACCESS_FINE_LOCATION)) {
                    explain(activity);
                } else {
                    request(activity);
                }
            }
        } else {
            showNotification();
        }

        return () -> {
            // Allow the caller to close this request if it no longer cares about the result
            closeNotification();
            mPrefs.unregisterOnSharedPreferenceChangeListener(preferenceListener);
        };
    }

    /**
     * Use the activity to request permissions if possible.
     */
    private void request(Activity activity) {
        activity.requestPermissions(new String[]{ACCESS_FINE_LOCATION},
                    REQUEST_P2P_PERMISSION_CODE);
    }

    private void explain(Activity activity) {
        // User denied, but asked us to use P2P, so explain and redirect to settings
        new AlertDialog.Builder(activity, android.R.style.Theme_DeviceDefault_Light_Dialog_Alert)
                .setMessage(mContext.getString(R.string.wifi_direct_permission_rationale))
                .setPositiveButton(R.string.fix, (dialog, which) -> request(activity))
                .show();
    }

    /**
     * Request location services be enabled globally.
     */
    private void requestLocation(Activity activity) {
        new AlertDialog.Builder(activity, android.R.style.Theme_DeviceDefault_Light_Dialog_Alert)
            .setMessage(mContext.getString(R.string.wifi_direct_location_rationale))
            .setPositiveButton(R.string.enable_location, (dialog, which) ->
                activity.startActivityForResult(new Intent(
                        Settings.ACTION_LOCATION_SOURCE_SETTINGS), REQUEST_LOCATION_ENABLE)
            )
            .setOnCancelListener(dialog -> {
                if (getState() == State.DENIED) {
                    setState(State.TEMPORARILY_DISABLED);
                }
            })
            .show();
    }

    private SharedPreferences.OnSharedPreferenceChangeListener listenForPreferenceChanges(
            P2pPermissionListener listener) {
        SharedPreferences.OnSharedPreferenceChangeListener preferenceListener =
                new SharedPreferences.OnSharedPreferenceChangeListener() {
                    @Override
                    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                                          String key) {
                        State state = getState();
                        if (state.isTerminal() || state == State.DENIED) {
                            listener.onP2pPermissionComplete(state == State.ALLOWED);
                            mPrefs.unregisterOnSharedPreferenceChangeListener(this);
                        }
                    }
                };
        mPrefs.registerOnSharedPreferenceChangeListener(preferenceListener);
        return preferenceListener;
    }

    /**
     * Deliver a notification to the user.
     */
    private void showNotification() {
        // Because we are not in an activity create a notification to do the work
        mNotificationManager.createNotificationChannel(new NotificationChannel(
                CHANNEL_ID_CONNECTIONS, mContext.getString(R.string.connections),
                NotificationManager.IMPORTANCE_HIGH));

        Intent proceedIntent = new Intent(mContext, AddPrintersActivity.class);
        proceedIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        proceedIntent.putExtra(AddPrintersFragment.EXTRA_FIX_P2P_PERMISSION, true);
        PendingIntent proceedPendingIntent = PendingIntent.getActivity(mContext, 0,
                proceedIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        Notification.Action fixAction = new Notification.Action.Builder(
                Icon.createWithResource(mContext, R.drawable.ic_printservice),
                mContext.getString(R.string.fix), proceedPendingIntent).build();

        Intent cancelIntent = new Intent(mContext, BuiltInPrintService.class)
                .setAction(BuiltInPrintService.ACTION_P2P_PERMISSION_CANCEL);
        PendingIntent cancelPendingIndent = PendingIntent.getService(mContext,
                BuiltInPrintService.P2P_PERMISSION_REQUEST_ID, cancelIntent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        Intent disableIntent = new Intent(mContext, BuiltInPrintService.class)
                .setAction(BuiltInPrintService.ACTION_P2P_DISABLE);
        PendingIntent disablePendingIndent = PendingIntent.getService(mContext,
                BuiltInPrintService.P2P_PERMISSION_REQUEST_ID, disableIntent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        Notification.Action disableAction = new Notification.Action.Builder(
                Icon.createWithResource(mContext, R.drawable.ic_printservice),
                mContext.getString(R.string.disable_wifi_direct), disablePendingIndent).build();

        Notification notification = new Notification.Builder(mContext, CHANNEL_ID_CONNECTIONS)
                .setSmallIcon(R.drawable.ic_printservice)
                .setContentText(mContext.getString(R.string.wifi_direct_problem))
                .setStyle(new Notification.BigTextStyle().bigText(
                        mContext.getString(R.string.wifi_direct_problem)))
                .setAutoCancel(true)
                .setContentIntent(proceedPendingIntent)
                .setDeleteIntent(cancelPendingIndent)
                .addAction(fixAction)
                .addAction(disableAction)
                .build();

        mNotificationManager.notify(BuiltInPrintService.P2P_PERMISSION_REQUEST_ID, notification);
    }

    /**
     * Return the current {@link State}.
     */
    public State getState() {
        // Look up stored state
        String stateString = mPrefs.getString(STATE_KEY, State.DENIED.name());
        State state = State.valueOf(stateString);

        if (state == State.DISABLED) {
            // If disabled do no further checking
            return state;
        }

        boolean allowed = isLocationEnabled() && hasP2pPermission();
        if (allowed && state != State.ALLOWED) {
            // Upgrade state if now allowed
            state = State.ALLOWED;
            setState(state);
        } else if (!allowed && state == State.ALLOWED) {
            state = State.DENIED;
            setState(state);
        }
        return state;
    }

    /**
     * Return true if location services are enabled.
     */
    private boolean isLocationEnabled() {
        LocationManager manager = (LocationManager) mContext.getSystemService(
                Context.LOCATION_SERVICE);
        return manager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
    }

    /**
     * Close any outstanding notification.
     */
    void closeNotification() {
        mNotificationManager.cancel(BuiltInPrintService.P2P_PERMISSION_REQUEST_ID);
    }

    /**
     * The current P2P permission request state.
     */
    public enum State {
        // The user has not granted permissions.
        DENIED,
        // The user did not grant permissions this time but try again next time.
        TEMPORARILY_DISABLED,
        // The user explicitly disabled or chose not to enable P2P.
        DISABLED,
        // Permissions are granted.
        ALLOWED;

        /** Return true if the user {@link State} is at a final permissions state. */
        public boolean isTerminal() {
            return this != DENIED;
        }
    }

    /**
     * Listener for determining when a P2P permission request is complete.
     */
    public interface P2pPermissionListener {
        /**
         * Invoked when it is known that the user has allowed or denied the permission request.
         */
        void onP2pPermissionComplete(boolean allowed);
    }

    /**
     * A closeable request for grant of P2P permissions.
     */
    public interface P2pPermissionRequest extends AutoCloseable {
        @Override
        void close();
    }
}