在 Android M(预览)中,用户可以选择特定应用并检索特定权限。
所以我问如何在运行时检查授权权限?
答案 0 :(得分:52)
很好!!
我刚刚发现我的需要,我们可以通过以下方式检查是否授予了权限:
checkSelfPermission(Manifest.permission.READ_CONTACTS)
if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant
return;
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! do the
// calendar task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'switch' lines to check for other
// permissions this app might request
}
}
答案 1 :(得分:35)
请尝试使用简单的请求代码 https://www.learn2crack.com/2015/10/android-marshmallow-permissions.html
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
private boolean checkAndRequestPermissions() {
int camera = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
int storage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
int loc = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
int loc2 = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (camera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
}
if (storage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (loc2 != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
if (loc != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (!listPermissionsNeeded.isEmpty())
{
ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray
(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
答案 2 :(得分:7)
尝试检查运行时权限:
private void checkRunTimePermission() {
String[] permissionArrays = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissionArrays, 11111);
} else {
// if already permition granted
// PUT YOUR ACTION (Like Open cemara etc..)
}
}
检查运行时权限:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean openActivityOnce = true;
boolean openDialogOnce = true;
if (requestCode == 11111) {
for (int i = 0; i < grantResults.length; i++) {
String permission = permissions[i];
isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
// user rejected the permission
boolean showRationale = shouldShowRequestPermissionRationale(permission);
if (!showRationale) {
//execute when 'never Ask Again' tick and permission dialog not show
} else {
if (openDialogOnce) {
alertView();
}
}
}
}
if (isPermitted)
if (isPermissionFromGallery)
openGalleryFragment();
}
}
处理权限结果:
private void alertView() {
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);
dialog.setTitle("Permission Denied")
.setInverseBackgroundForced(true)
//.setIcon(R.drawable.ic_info_black_24dp)
.setMessage("Without those permission the app is unable to save your profile. App needs to save profile image in your external storage and also need to get profile image from camera or external storage.Are you sure you want to deny this permission?")
.setNegativeButton("I'M SURE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
dialoginterface.dismiss();
}
})
.setPositiveButton("RE-TRY", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
dialoginterface.dismiss();
checkRunTimePermission();
}
}).show();
}
设置自定义提醒:
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildLayoutPosition(view) == 0) {
outRect.top = space;
} else {
outRect.top = 0;
}
}}
答案 3 :(得分:3)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define Pi 3.141592
int hypotri(void);
int disBePoints(void);
int circle(int y);
int square(void);
typedef enum calcOption
{
distance=1,
hypotenuse=2,
areaC=3,
areaR=4,
areaS=5
}option;
int main(void)
{
float finish=0, y=0,i=0;
printf("Welcome to my calculator!\n");
while(i!=6)
{
printf("Welcome to my calculator!\nchoose option:\n1 - Calc distance between 2 points\n2 - Calc hypotenuse of triangle\n3 - Calc area and perimeter of circle\n4 - Calc area of rectangle\n5 - Calc area of square\n6 - Exit");
scanf("%d",&option);
calcOption option;
option=calcOPtion(i);
switch(option)
{
case distance:
{
disBePoints();
("the distance is %f",finish);
break;
}
case hypotenuse:
{
hypotri();
("the hypotenuse is %f",finish);
break;
}
case areaC:
{
for(y=1;y>2;y++)
{
circle(y);
if(y=1)
{
("the perimeter is %f",finish);
}
else
{
("the area is %f",finish);
}
break;
}
}
case areaR:
{
square();
("the hypotenuse is %f",finish);
break;
}
case areaS:
{
square();
("the hypotenuse is %f",finish);
break;
}
default:
{
printf("dont mess with me enter number between 1-6");
}
}
}
system("pause");
return 0;
}
/** why= to see what is the distance between any points\n
input=none
output=none
**/
int disBePoints(void)
{
float xOne=0,xTwo=0,yOne=0,yTwo=0, finish=0;
printf("Enter point 1 coordinates:");
scanf("%f%f",&xOne,&yOne);
printf("\nEnter point 2 coordinates:");
scanf("%f%f",&xTwo,&yTwo);
finish=sqrt(pow(xTwo-xOne,2)+pow(yTwo-yOne,2));
return finish;
}
/** why= to see what is the hypotenuse of the triange
input=none
output=none
**/
int hypotri(void)
{
float x=0,y=0,finish;
printf("Enter 2 sides of the triangle:");
scanf("%f%f",&x,&y);
finish=sqrt(pow(x,2)+pow(y,2));
return finish;
}
/** why= to see what is primeter and the area of the circle
input=none
output=none
**/
int circle(int y)
{
float radius=0,finish=0;
printf("Enter circle radius:");
scanf("%f",&radius);
if(y=1)
{
finish=radius*2*Pi;
}
else
{
finish=pow(radius,2)*Pi;
}
return finish;
}
/** why= to see what is the area of the rectangle or the square
input=none
output=none
**/
int square(void)
{
float yside=0,xside=0,finish=0;
printf("Enter lentgh and width:");
scanf("%f%f",&xside,&yside);
finish=yside*xside;
return finish;
}
答案 4 :(得分:3)
在您的build.gradle
dependencies{
implementation 'com.karumi:dexter:4.2.0'
}
此示例请求WRITE_EXTERNAL_STORAGE.
Dexter.withActivity(this)
.withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
// permission is granted, open the camera
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
// check for permanent denial of permission
if (response.isPermanentlyDenied()) {
// navigate user to app settings
}
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
检查此答案here
答案 5 :(得分:2)
对于简单使用权限,您可以使用此lib:http://hotchemi.github.io/PermissionsDispatcher/
答案 6 :(得分:1)
对于位置运行时权限
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("yes","yes");
} else {
Log.d("yes","no");
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
答案 7 :(得分:0)
您还可以通过以下代码段查询为向后兼容;
int hasPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
//Do smthng
}
答案 8 :(得分:0)
原始(不是我的)帖子here
对于特殊权限,例如android.Manifest.permission.PACKAGE_USAGE_STATS
使用AppOpsManager
:
的科特林强>
private fun hasPermission(permission:String, permissionAppOpsManager:String): Boolean {
var granted = false
if (VERSION.SDK_INT >= VERSION_CODES.M) {
// requires kitkat
val appOps = applicationContext!!.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
// requires lollipop
val mode = appOps.checkOpNoThrow(permissionAppOpsManager,
android.os.Process.myUid(), applicationContext!!.packageName)
if (mode == AppOpsManager.MODE_DEFAULT) {
granted = applicationContext!!.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
} else {
granted = mode == AppOpsManager.MODE_ALLOWED
}
}
return granted
}
以及代码中的任何地方:
val permissionAppOpsManager = AppOpsManager.OPSTR_GET_USAGE_STATS
val permission = android.Manifest.permission.PACKAGE_USAGE_STATS
val permissionActivity = Settings.ACTION_USAGE_ACCESS_SETTINGS
if (hasPermission(permission, permissionAppOpsManager)) {
Timber.i("has permission: $permission")
// do here what needs permission
} else {
Timber.e("has no permission: $permission")
// start activity to get permission
startActivity(Intent(permissionActivity))
}
可以获得的其他权限
答案 9 :(得分:0)
在git中查看以下库:
实施:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.manoj140220:RuntimePermission:1.0.3'
}
new RuntimePermission({Current Class Object}, String[] , {ActvityContext});
String[] : permission array.
example : String[] permissionArray = {Manifest.permission.CAMERA, Manifest.permission.BODY_SENSORS,...}
Implement : {PermissionNotify}
interface notifier methods.
@Override
public void notifyPermissionGrant() {
}
@Override
public void notifyPermissionDeny() {
}