Android6.0权限
程序员文章站
2024-03-17 10:57:58
...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 如果targetSDKVersion >= 23,就要申请好权限。如果您的App没有适配到Android6.0(即targetSDKVersion < 23),那么就直接执行下一步
if (Build.VERSION.SDK_INT >= 23) {
checkAndRequestPermission();
}else{
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void checkAndRequestPermission() {
List<String> lackedPermission = new ArrayList<String>();
if (!(checkSelfPermission(android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)) {
lackedPermission.add(android.Manifest.permission.READ_PHONE_STATE);
}
if (!(checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
lackedPermission.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!(checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
lackedPermission.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
if (lackedPermission.size() == 0) {
//如果没有缺少的权限,直接执行下一步
}else {
// 请求所缺少的权限,在onRequestPermissionsResult中再看是否获得权限,如果获得权限就可以调用SDK,否则不要调用SDK。
String[] requestPermissions = new String[lackedPermission.size()];
lackedPermission.toArray(requestPermissions);
requestPermissions(requestPermissions, 1024);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1024 && hasAllPermissionsGranted(grantResults)) {
//如果用户授权则执行下一步
} else {
// 如果用户没有授权,那么应该说明意图,引导用户去设置里面授权。
Toast.makeText(this, "应用缺少必要的权限!请点击\"权限\",打开所需要的权限。", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
private boolean hasAllPermissionsGranted(int[] grantResults) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
return false;
}
}
return true;
}
}
上一篇: android自定义广播
下一篇: Java之使用IO流输入输出