从6.0开始,获得用户权限已经不在是通过安装程序时获得。这种方法简化了程序安装的过程,因为不需要用户在安装或者更新时授予权限。这也给了用户控制app的功能。例如,用户可以选择给一个app打开相机的权限而不是设备的位置。用户可以在任何时候去收回权限,通过app的Setting。
系统权限被分成了两类,normal和dangerous
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_CALENDAR); if(permissionCheck == PackageManager.PERMISSION_GRANTED){ Toast.makeText(MainActivity.this,"授予",Toast.LENGTH_SHORT).show(); }else if(permissionCheck == PackageManager.PERMISSION_DENIED){ Toast.makeText(MainActivity.this,"拒绝",Toast.LENGTH_SHORT).show(); }如果返回值的结果和PackageManager.PERMISSION_DENIED一致,则必须让app显示的去询问用户是否授予权限
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS); if(permissionCheck == PackageManager.PERMISSION_GRANTED){ Toast.makeText(MainActivity.this,"授予",Toast.LENGTH_SHORT).show(); }else if(permissionCheck == PackageManager.PERMISSION_DENIED){ //没有该权限 if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.READ_CONTACTS)){ Log.d("TAG","弹出询问"); Toast.makeText(MainActivity.this,"123",Toast.LENGTH_SHORT).show(); ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, 123); }else { Log.d("TAG","也需要弹出询问(已经被拒绝并且不再询问,已经被拒绝通过上个判断结果得出" + "需要跟用户解释某些功能无法使用因为权限原因" + "之前用户关闭这个功能并且不让询问了,需要用户手动更改"+ ""); Toast.makeText(MainActivity.this,"123",Toast.LENGTH_SHORT).show(); ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, 123); } }
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { Toast.makeText(MainActivity.this,grantResults[0]+"~~",Toast.LENGTH_SHORT).show(); switch (requestCode){ case 123: if(grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_GRANTED){ Toast.makeText(MainActivity.this,"弹出dialog,用户授权,用户同意",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MainActivity.this,"弹出dialog,用户授权,用户不同意,提醒用户没有该权限不能使用功能",Toast.LENGTH_SHORT).show(); } break; default: } }