java - java Android 6.0权限

  显示原文与译文双语对照的内容
101 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页,并同时调用它们来激活。

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

示例( 忘记了google应用程序的名称:( )
应用需要短信,联系人和照相机

应用程序要求( 并制作了一个对话框 page1-3 ) 激活短信,激活联系人然后照相机。所以这个google应用程序将所有 3个必需的权限一起调用,我的问题是如何 achive?

时间:原作者:0个回答

85 3

将所有 4权限包括在ActivityCompat.requestPermissions(...)电话和安卓会自动将它们按你所提到的方式自动分页。

我有一个 helper 方法来检查多个权限,看看它们是否没有被授予。

public static boolean hasPermissions(Context context, String... permissions) {
 if (context!= null && permissions!= null) {
 for (String permission : permissions) {
 if (ActivityCompat.checkSelfPermission(context, permission)!= PackageManager.PERMISSION_GRANTED) {
 return false;
 }
 }
 }
 return true;
}

然后只需发送所有的权限。安卓将只要求对它的所需的。

//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);
}
原作者:
95 3

小代码:

 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;
 }
 }
}

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

原作者:
80 0

在 fragment 中

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");
 }
 }
 }
 }
 }
}

}

原作者:
60 0

很容易,这样

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();
 }
 }
 }
}
原作者:
99 4

下面的方法是关于

  • 动态请求权限;
  • 如果用户拒绝任何权限,则显示 AlertDialog
  • 循环直到用户接受权限( s )

为权限方法创建"static"类

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();
 }
原作者:
78 4

我已经成功地实现了一次多个权限的简单代码。按照下面的步骤 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:Now 检查权限

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;
 }
}
原作者:
73 4

我的方法是基于 Nicks'回答并希望有一点可以用于多个( 如果需要的话,不仅仅是两个) 权限。建议添加单个责任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:nn");
 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消息。

在 Activity 中使用的示例:

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);
}

希望这对某人有用。

原作者:
...