PermissionsUtil.java revision 4f76e61f8e0a0cf48a0f80fa9ec0ea60adbf536f
1/* 2 * Copyright (C) 2015 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.contacts.common.util; 18 19import android.Manifest.permission; 20import android.content.Context; 21import android.content.pm.PackageManager; 22 23/** 24 * Utility class to help with runtime permissions. 25 */ 26public class PermissionsUtil { 27 // Each permission in this list is a cherry-picked permission from a particular permission 28 // group. Granting a permission group enables access to all permissions in that group so we 29 // only need to check a single permission in each group. 30 // Note: This assumes that the app has correctly requested for all the relevant permissions 31 // in its Manifest file. 32 public static final String PHONE = permission.CALL_PHONE; 33 public static final String CONTACTS = permission.READ_CONTACTS; 34 public static final String LOCATION = permission.ACCESS_FINE_LOCATION; 35 36 private static Boolean sHasPhonePermissions; 37 private static Boolean sHasContactsPermissions; 38 private static Boolean sHasLocationPermissions; 39 40 public static boolean hasPhonePermissions(Context context) { 41 if (sHasPhonePermissions == null) { 42 sHasPhonePermissions = hasPermission(context, PHONE); 43 } 44 return sHasPhonePermissions; 45 } 46 47 public static boolean hasContactsPermissions(Context context) { 48 if (sHasContactsPermissions == null) { 49 sHasContactsPermissions = hasPermission(context, CONTACTS); 50 } 51 return sHasContactsPermissions; 52 } 53 54 public static boolean hasLocationPermissions(Context context) { 55 if (sHasLocationPermissions == null) { 56 sHasLocationPermissions = hasPermission(context, LOCATION); 57 } 58 return sHasLocationPermissions; 59 } 60 61 /** 62 * To be called during various activity lifecycle events to update the cached versions of the 63 * permissions. 64 * 65 * @param context A valid context. 66 */ 67 public static void updateCachedPermissions(Context context) { 68 hasPermission(context, PHONE); 69 hasPermission(context, CONTACTS); 70 hasPermission(context, LOCATION); 71 } 72 73 public static boolean hasPermission(Context context, String permission) { 74 return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; 75 } 76} 77