Android 6.0多个权限

我知道Android 6.0具有新的权限,我知道我可以用这样的东西来调用它们

if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, PERMISSION_WRITE_STORAGE); } 

今天我看到一个需要3个权限的Google应用程序:联系人,短信和相机。 它正在制作第1-3页,并同时将它们全部召集起来激活。

任何人都可以告诉我如何可以调用4个权限来激活同时像短信,相机,联系人和存储?

例子(忘了谷歌应用程序的名称:()
该应用程序需要短信,联系人和相机

该应用程序问我(并做了一个对话页1-3)激活短信,激活联系人,然后相机。 所以这个谷歌应用程序一起调用所有3个必要的权限,我的问题是我如何达到相同?

只需在ActivityCompat.requestPermissions(...)调用中包含所有4个权限,Android就会像您提到的那样自动将它们分页。

我有一个帮助方法来检查多个权限,看看他们中的任何一个都没有被授予。

 public static boolean hasPermissions(Context context, String... permissions) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } 

然后发送所有的权限。 Android只会询问需要的内容。

 // The request code used in ActivityCompat.requestPermissions() // and returned in the Activity's onRequestPermissionsResult() int PERMISSION_ALL = 1; String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS, Manifest.permission.CAMERA}; if(!hasPermissions(this, PERMISSIONS)){ ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL); } 

下面是具有多个权限请求的详细示例:

该应用程序在启动时需要2个权限。 SEND_SMS和ACCESS_FINE_LOCATION(都在manifest.xml中提到)。

我正在使用支持库v4准备处理Android的棉花糖之前,所以不需要检查构build版本。

一旦应用程序启动,它会一起请求多个权限。 如果这两个权限都被授予,则正常stream程进行。

在这里输入图像描述

在这里输入图像描述

 public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(checkAndRequestPermissions()) { // carry on the normal flow, as the case of permissions granted. } } private boolean checkAndRequestPermissions() { int permissionSendMessage = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS); int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); List<String> listPermissionsNeeded = new ArrayList<>(); if (locationPermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.SEND_SMS); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS); return false; } return true; } 

ContextCompat.checkSelfPermission(),ActivityCompat.requestPermissions(),ActivityCompat.shouldShowRequestPermissionRationale()是支持库的一部分。

如果没有授予一个或多个权限,则ActivityCompat.requestPermissions()将请求权限,控制权将转到onRequestPermissionsResult()callback方法。

您应该在onRequestPermissionsResult()callback方法中检查shouldShowRequestPermissionRationale()标志的值。

只有两种情况:

案例1: – 任何时候用户点击拒绝权限(包括第一次),它将返回true。 所以当用户否认的时候,我们可以展示更多的解释,不断的询问

情况2: – 只有当用户select“不再询问”时,才会返回false。 在这种情况下,我们可以继续使用有限的function,并指导用户从更多function的设置中激活权限,或者如果权限对于应用程序来说是微不足道的,我们可以完成设置。

情况1

在这里输入图像描述

CASE-2

在这里输入图像描述

  @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { Log.d(TAG, "Permission callback called-------"); switch (requestCode) { case REQUEST_ID_MULTIPLE_PERMISSIONS: { Map<String, Integer> perms = new HashMap<>(); // Initialize the map with both permissions perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED); perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); // Fill with actual results from user if (grantResults.length > 0) { for (int i = 0; i < permissions.length; i++) perms.put(permissions[i], grantResults[i]); // Check for both permissions if (perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "sms & location services permission granted"); // process the normal flow //else any one or both the permissions are not granted } else { Log.d(TAG, "Some permissions are not granted ask again "); //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission // // shouldShowRequestPermissionRationale will return true //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup. if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { showDialogOK("SMS and Location Services Permission required for this app", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: checkAndRequestPermissions(); break; case DialogInterface.BUTTON_NEGATIVE: // proceed with logic by disabling the related features or quit the app. break; } } }); } //permission is denied (and never ask again is checked) //shouldShowRequestPermissionRationale will return false else { Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG) .show(); // //proceed with logic by disabling the related features or quit the app. } } } } } } private void showDialogOK(String message, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", okListener) .create() .show(); } 

小码:

  public static final int MULTIPLE_PERMISSIONS = 10; // code you want. String[] permissions= new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}; if (checkPermissions()) // permissions granted. } private boolean checkPermissions() { int result; List<String> listPermissionsNeeded = new ArrayList<>(); for (String p:permissions) { result = ContextCompat.checkSelfPermission(getActivity(),p); if (result != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(p); } } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS ); return false; } return true; } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MULTIPLE_PERMISSIONS:{ if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ // permissions granted. } else { String permissions = ""; for (String per : permissionsList) { permissions += "\n" + per; } // permissions list of don't granted permission } return; } } } 

API权限列表中的Android权限正常权限和危险权限23

这很容易,这样做

 private static final int REQUEST_READ_PHONE_STATE = 110 , REQUEST_ACCESS_FINE_LOCATION = 111, REQUEST_WRITE_STORAGE = 112; 

在你的onCreate

  //request permission boolean hasPermissionPhoneState = (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED); if (!hasPermissionPhoneState) { ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE); } boolean hasPermissionLocation = (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED); if (!hasPermissionLocation) { ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_ACCESS_FINE_LOCATION); } boolean hasPermissionWrite = (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); if (!hasPermissionWrite) { ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE); } 

然后检查结果

 @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_READ_PHONE_STATE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show(); //reload my activity with permission granted or use the features what required the permission finish(); startActivity(getIntent()); } else { Toast.makeText(LoginActivity.this, "The app was not allowed to get your phone state. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show(); } } case REQUEST_ACCESS_FINE_LOCATION: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show(); //reload my activity with permission granted or use the features what required the permission finish(); startActivity(getIntent()); } else { Toast.makeText(LoginActivity.this, "The app was not allowed to get your location. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show(); } } case REQUEST_WRITE_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show(); //reload my activity with permission granted or use the features what required the permission finish(); startActivity(getIntent()); } else { Toast.makeText(LoginActivity.this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show(); } } } } 

在片段

 public class Homefragment extends Fragment { View hfrag; Context context; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //first we must check the permissions are already granted hfrag = inflater.inflate(R.layout.home, container, false); context = getActivity(); checkAndRequestPermissions(); } } private boolean checkAndRequestPermissions() { int permissionSendMessage = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS); int contactpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS); int writepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE); int callpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE); int receivepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.RECEIVE_SMS); int locationpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION); List<String> listPermissionsNeeded = new ArrayList<>(); if (locationpermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (contactpermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.GET_ACCOUNTS); } if (writepermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.READ_SMS); } if (receivepermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.RECEIVE_SMS); } if (callpermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.CALL_PHONE); } if (!listPermissionsNeeded.isEmpty()) { requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS); return false; } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_ID_MULTIPLE_PERMISSIONS) { if (grantResults.length > 0) { for (int i = 0; i < permissions.length; i++) { if (permissions[i].equals(Manifest.permission.GET_ACCOUNTS)) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { Log.e("msg", "accounts granted"); } } else if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { Log.e("msg", "storage granted"); } } else if (permissions[i].equals(Manifest.permission.CALL_PHONE)) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { Log.e("msg", "call granted"); } } else if (permissions[i].equals(Manifest.permission.RECEIVE_SMS)) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { Log.e("msg", "sms granted"); } } else if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { Log.e("msg", "location granted"); } } } } } } 

}

以下方法是关于

  • dynamic询问权限;
  • 如果用户拒绝任何权限,则显示AlertDialog
  • 循环,直到用户接受许可(S)

为权限方法创build一个“静态”类

 public class PermissionsUtil { public static final int PERMISSION_ALL = 1; public static boolean doesAppNeedPermissions(){ return android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1; } public static String[] getPermissions(Context context) throws PackageManager.NameNotFoundException { PackageInfo info = context.getPackageManager().getPackageInfo( context.getPackageName(), PackageManager.GET_PERMISSIONS); return info.requestedPermissions; } public static void askPermissions(Activity activity){ if(doesAppNeedPermissions()) { try { String[] permissions = getPermissions(activity); if(!checkPermissions(activity, permissions)){ ActivityCompat.requestPermissions(activity, permissions, PERMISSION_ALL); } } catch(Exception e) { e.printStackTrace(); } } } public static boolean checkPermissions(Context context, String... permissions){ if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { for (String permission : permissions) { if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } } 

在MainActivity.java中

  private void checkPermissions(){ PermissionsUtil.askPermissions(this); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case PermissionsUtil.PERMISSION_ALL: { if (grantResults.length > 0) { List<Integer> indexesOfPermissionsNeededToShow = new ArrayList<>(); for(int i = 0; i < permissions.length; ++i) { if(ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) { indexesOfPermissionsNeededToShow.add(i); } } int size = indexesOfPermissionsNeededToShow.size(); if(size != 0) { int i = 0; boolean isPermissionGranted = true; while(i < size && isPermissionGranted) { isPermissionGranted = grantResults[indexesOfPermissionsNeededToShow.get(i)] == PackageManager.PERMISSION_GRANTED; i++; } if(!isPermissionGranted) { showDialogNotCancelable("Permissions mandatory", "All the permissions are required for this app", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { checkPermissions(); } }); } } } } } } private void showDialogNotCancelable(String title, String message, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton("OK", okListener) .setCancelable(false) .create() .show(); } 

我已经成功实现了简单代码一次多个权限。 按照下面的步骤1:制作Utility.java类,如下所示

 public class Utility { public static final int MY_PERMISSIONS_REQUEST = 123; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public static boolean checkPermissions(Context context, String... permissions) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permission)) { ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE,Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST); } else { ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE,Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST); } return false; } } } return true; } } 

2:现在打电话

 boolean permissionCheck = Utility.checkPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE, Manifest.permission.GET_ACCOUNTS); 

在您的Activity onCreate()或根据您的逻辑。

3:现在在执行特定任务的操作之前检查权限

 if (permissionCheck) { performTaskOperation();//this method what you need to perform } else { Toast.makeText(this, "Need permission ON.", Toast.LENGTH_SHORT).show(); } 

4:现在在你的Activity中实现onRequestPermissionsResult()方法如下

  @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case Utility.MY_PERMISSIONS_REQUEST: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (userChoosenTask.equals("STORAGE")) performTaskOperation();//this method what you need to perform } break; } } 

我发现这是来自Google的github的运行时权限示例。

  private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}; private static final int REQUEST_CONTACTS = 1; ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS); 

请检查本文中的“一次询问多个权限”部分:

你需要知道的关于Android M权限的东西

这个解释非常好,也可以触及你没有想到的其他相关话题。

短而甜蜜:)。 我相信什么

 int PERMISSION_ALL = 1; String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; // List of permissions required public void askPermission() { for (String permission : PERMISSIONS) { if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { requestPermissions(PERMISSIONS, PERMISSION_ALL); return; } } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case 1:{ if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){ //Do your work. } else { Toast.makeText(this, "Until you grant the permission, we cannot proceed further", Toast.LENGTH_SHORT).show(); } return; } } 

像这样使用助手(权限名称无关紧要)。

 public class MyPermission { private static final int PERMISSION_REQUEST_ALL = 127; private MainActivity mMainActivity; MyPermission(MainActivity mainActivity) { mMainActivity = mainActivity; } public static boolean hasPermission(String permission, Context context) { if (isNewPermissionModel()) { return (ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED); } return true; } private static boolean hasPermissions(Context context, String... permissions) { if (isNewPermissionModel() && context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } private static boolean shouldShowRationale(Activity activity, String permission) { return isNewPermissionModel() && ActivityCompat.shouldShowRequestPermissionRationale(activity, permission); } private static boolean isNewPermissionModel() { return VERSION.SDK_INT > VERSION_CODES.LOLLIPOP_MR1; } /** * check all permissions */ void checkAll() { //check dangerous permissions, make request if need (Android will ask only for the ones it needs) String[] PERMISSIONS = { permission.READ_CALENDAR, permission.ACCESS_COARSE_LOCATION }; if (!hasPermissions(mMainActivity, PERMISSIONS)) { ActivityCompat.requestPermissions(mMainActivity, PERMISSIONS, PERMISSION_REQUEST_ALL); } } void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PERMISSION_REQUEST_ALL) { if (grantResults.length > 0) { //for not granted for (int i = 0; i < permissions.length; i++) { if (permissions[i].equals(permission.READ_CALENDAR)) { if (grantResults[i] != PackageManager.PERMISSION_GRANTED) { smartRequestPermissions(permission.READ_CALENDAR, R.string.permission_required_dialog_read_calendar); } } else if (permissions[i].equals(permission.ACCESS_COARSE_LOCATION)) { if (grantResults[i] != PackageManager.PERMISSION_GRANTED) { smartRequestPermissions(permission.ACCESS_COARSE_LOCATION, R.string.permission_required_dialog_access_coarse_location); } } } } } } private void smartRequestPermissions(final String permissionName, int permissionRequiredDialog) { if (shouldShowRationale(mMainActivity, permissionName)) {// If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false. //Show an explanation to the user with action mMainActivity.mSnackProgressBarManager.show( new SnackProgressBar( SnackProgressBar.TYPE_ACTION, mMainActivity.getString(permissionRequiredDialog) ) .setAction("OK", new OnActionClickListener() { @Override public void onActionClick() { checkAll(); } }) .setSwipeToDismiss(true).setAllowUserInput(true) , MainActivity.SNACKBAR_WARNING_DURATION ); } // else do nothing } 

}

我的方法是基于尼克斯的答案,希望是更多的可用多个(多达需要,而不是两个)的权限。 build议增加单个责任PermissionsHelper类:

 import android.app.Activity; import android.app.AlertDialog; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PermissionsHelper { private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 100; // any code you want. public void checkAndRequestPermissions(Activity activity, String... permissions) { List<String> listPermissionsNeeded = new ArrayList<>(); for (String permission : permissions) { if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(permission); } } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS); } } public void onRequestPermissionsResult(Activity activity, int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_ID_MULTIPLE_PERMISSIONS: { Map<String, Integer> perms = new HashMap<>(); for (String permission : permissions) { perms.put(permission, PackageManager.PERMISSION_GRANTED); } if (grantResults.length > 0) { for (int i = 0; i < permissions.length; i++) perms.put(permissions[i], grantResults[i]); boolean allPermissionsGranted = true; for (String permission1 : permissions) { allPermissionsGranted = allPermissionsGranted && (perms.get(permission1) == PackageManager.PERMISSION_GRANTED); } if (allPermissionsGranted) { Log.d(PermissionsHelper.class.getSimpleName(), "onRequestPermissionsResult: all permissions granted"); } else { for (String permission2 : perms.keySet()) if (perms.get(permission2) == PackageManager.PERMISSION_GRANTED) perms.remove(permission2); StringBuilder message = new StringBuilder("The app has not been granted permissions:\n\n"); for (String permission : perms.keySet()) { message.append(permission); message.append("\n"); } message.append("\nHence, it cannot function properly." + "\nPlease consider granting it this permission in phone Settings."); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.permission_required) .setMessage(message) .setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.cancel()); AlertDialog alert = builder.create(); alert.show(); } } } } } 

}

如果用户还没有授予一个或多个必需的权限,则会向他显示详细的AlertDialog消息。

活动中的使用示例:

 private PermissionsHelper permissionsHelper; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkPermissions(); //any other code } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { permissionsHelper.onRequestPermissionsResult(this, requestCode, permissions, grantResults); } private void checkPermissions() { permissionsHelper = new PermissionsHelper(); permissionsHelper.checkAndRequestPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION); } 

希望这会对某人有用。