2017-08-29 152 views
0

这是调用函数时询问权限的代码。使用SDK的Android运行时权限

public void sendMessage(View view) { 
     if(Build.VERSION.SDK_INT <23 || checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){ 
      Toast.makeText(this,"Permission has granted, very nice.",Toast.LENGTH_SHORT).show(); 
     } 
     else{ 
      if(!shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){ 
       Toast.makeText(this,"This permission is required for this action, what a pitty.",Toast.LENGTH_SHORT).show(); 
      } 
      else{ 
       requestPermissions(new String[]{Manifest.permission.CAMERA},100); 
       Toast.makeText(this,"If you wanna do that, you have to give permission.",Toast.LENGTH_SHORT).show(); 
      } 
     } 
    }` 

这是AndroidManifest.xml中

<uses-permission android:name="android.permission.CAMERA" /> 

问题是。

在这种情况下,在SDK 21的 - >它会在安装应用时询问权限。 at SDK 25 - >安装时不会请求权限,但当函数调用时

是否该结构是正确的?

回答

0
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
public static boolean checkCameraPermission(final Context context) { 
    int currentAPIVersion = Build.VERSION.SDK_INT; 
    if (currentAPIVersion >= Build.VERSION_CODES.M) { 
     if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { 
      if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.CAMERA)) { 
       AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context); 
       alertBuilder.setCancelable(true); 
       alertBuilder.setTitle("Permission necessary"); 
       alertBuilder.setMessage("Camera permission is necessary"); 
       alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { 
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
        public void onClick(DialogInterface dialog, int which) { 
         ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); 
        } 
       }); 
       AlertDialog alert = alertBuilder.create(); 
       alert.show(); 
      } else { 
       ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); 
      } 
      return false; 
     } else { 
      return true; 
     } 
    } else { 
     return true; 
    } 
} 

//检查许可,这样

if(checkCameraPermission()){ 
    openCamera(); 
} // no need to write else part,.. it will automatically ask for permission from user. 

获准后

@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
    switch (requestCode) { 
     case Constant.MY_PERMISSIONS_REQUEST_CAMERA: 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       openCamera(); 
      } 
      break; 

    } 
}