在进行Content provider的练习的时候,获取相关的权限是至关重要的一步。不过老是容易忘记代码是怎么写的,特附上相关的代码以备复用
private static String[] PERMISSIONS = {
"android.permission.READ_CONTACTS",
"android.permission.WRITE_CONTACTS"
};
首先,确定好需要申请的所有权限; 其次在合适的地方进行权限的判定;判断权限是否被授权!
for (String permission : PERMISSIONS){
if( ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,PERMISSIONS,1);
}
}
最终,在每个activity中都有一个回调方法进行相应的重写:按照实际的业务需求进行重写即可!
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
if(grantResults.length > 0 && allPermissions(grantResults)){
All_GRANTED = true;
}
break;
}
}
private boolean allPermissions(int[] grantResults) {
for (int i : grantResults){
if(i != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}
|