Last active
December 11, 2015 04:12
-
-
Save atetc/514fb3f75e7166c3d094 to your computer and use it in GitHub Desktop.
Helpful util class template for Android M Permissions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ***.***.android.utils; | |
import android.Manifest; | |
import android.app.Activity; | |
import android.app.Fragment; | |
import android.content.Context; | |
import android.content.pm.PackageManager; | |
import android.support.v13.app.FragmentCompat; | |
import android.support.v4.app.ActivityCompat; | |
import android.support.v4.content.ContextCompat; | |
import android.support.v7.app.AppCompatActivity; | |
import static android.Manifest.permission.ACCESS_COARSE_LOCATION; | |
import static android.Manifest.permission.ACCESS_FINE_LOCATION; | |
/** | |
* @author Artur Vasilov | |
*/ | |
public class PermissionUtils { | |
private static final String PERMISSION_READ_GSERVICES = "com.google.android.providers.gsf.permission.READ_GSERVICES"; | |
public static final int LOCATION_PERMISSION_ID = 1; | |
private PermissionUtils() { | |
} | |
public static boolean checkPermissions(Context context, String... permissions) { | |
for (String permission : permissions) { | |
if (!checkPermission(context, permission)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
public static boolean checkPermission(Context context, String permission) { | |
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; | |
} | |
public static boolean isWriteExternalStorageGranted(Context context) { | |
return checkPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE); | |
} | |
public static boolean isDeviceInfoGranted(Context context) { | |
return checkPermission(context, Manifest.permission.READ_PHONE_STATE); | |
} | |
public static boolean isLocationPermissionGranted(Context context) { | |
return checkPermissions(context, ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION); | |
} | |
public static void requestPermissions(Object o, int permissionId, String... permissions) { | |
if (o instanceof Fragment) { | |
FragmentCompat.requestPermissions((Fragment) o, permissions, permissionId); | |
} else if (o instanceof Activity) { | |
ActivityCompat.requestPermissions((AppCompatActivity) o, permissions, permissionId); | |
} | |
} | |
public static void requestLocationPermission(Object o) { | |
String[] permissions = new String[]{ | |
ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, PERMISSION_READ_GSERVICES}; | |
requestPermissions(o, LOCATION_PERMISSION_ID, permissions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment