任何人都知道如何将棉花糖的支持添加到应用程序是棉花糖前应用的现有应用程序中吗?如何在运行时检查权限或如何编写用于在运行时检查权限的代码。以及在应用程序中编写代码的地方?
答案 0 :(得分:0)
对于运行时权限,我创建了这个通用的类,可以在任何地方使用 -
public class AppPermission {
public static boolean isMarshmallowPlusDevice() {
return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1;
}
@TargetApi(Build.VERSION_CODES.M)
public static boolean isPermissionRequestRequired(Activity activity, @NonNull String[] permissions, int requestCode) {
if (isMarshmallowPlusDevice() && permissions.length > 0) {
List<String> newPermissionList = new ArrayList<>();
for (String permission : permissions) {
if (PackageManager.PERMISSION_GRANTED != activity.checkSelfPermission(permission)) {
newPermissionList.add(permission);
}
}
if (newPermissionList.size() > 0) {
activity.requestPermissions(newPermissionList.toArray(new String[newPermissionList.size()]), requestCode);
return true;
}
}
return false;
}
}
然后将此代码放在需要用户许可的地方 -
if (!AppPermission.isPermissionRequestRequired(MyActivity.this, new String[]{"android.permission.GET_ACCOUNTS"},
REQUEST_APP_PERMISSION)) {
// Your code if permission available
}
在此之后,在Fragment
或Activity
中输入此代码 -
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_APP_PERMISSION:
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
int grantResult = grantResults[i];
switch (permission) {
case "android.permission.GET_ACCOUNTS":
if (PackageManager.PERMISSION_GRANTED == grantResult) {
// Your code
}
break;
}
}
break;
}
}
以上代码适用于GET_ACCOUNTS
的请求权限,您可以将其更改为所需的任何内容。
答案 1 :(得分:0)
您可以参考Marshmellow的官方文档:
https://developer.android.com/training/permissions/requesting.html
根据此文档,在使用时授予权限是Android 6.0(Marshmallow)中引入的功能,因此我担心在以前的版本中无法实现。
但是,如果用户使用的是CyanogenMod
或MIUI
手机,则会有应用程序将Android应用库存的权限模型包装起来,并使动态权限成为可能。
答案 2 :(得分:0)
First check if the device is Android 6.0 by using below code
here is the example of read contacts
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1){
// here check wheather runtime permission is granted or not
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// ask for permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
else
return;
}
Don't forget to define permission in manifest fileYou can check permission in Home Screen please follow the link below
https://developer.android.com/training/permissions/requesting.html