我写的android权限申请代码requestPermission()

March 8, 2022

public class MainActivity extends AppCompatActivity {

private final static String[] PERMISSIONS=new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION};
private final static int REQUEST_CODE_PERMISSION=1;
private final static int REQUEST_CODE_SETTINGS=2;
private TextView textView;

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE_SETTINGS) {
        recreate();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView=findViewById(R.id.id_text_view);
    if(requestPermission(PERMISSIONS)){ //请求权限
        continueNext();//继续运行程序
    }

}

private void continueNext() {
    //获得权限后,继续运行的代码
    textView.setText("成功");
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    boolean valid=true;
    for(String permission:permissions){
        if(!shouldShowRequestPermissionRationale(permission)) valid=false; //某项权限被禁止并不再询问
    }
    if (valid) {
        recreate();//如果某项权限没通过,刷新本页,会继续请求
    }else {
        //某项权限被禁止并不再询问,则转到程序的设置页
        new AlertDialog.Builder(this).setMessage("正常运行本程序,需要某些权限,请设置!").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent,REQUEST_CODE_SETTINGS);
            }
        }).show();
    }
}

private boolean requestPermission(String[] permissions){
    boolean valid=true;
    List<String> requestPermissions=new ArrayList<>();
    for(String permission:permissions){
        if(ActivityCompat.checkSelfPermission(this,permission)!= PackageManager.PERMISSION_GRANTED){
            requestPermissions.add(permission);
            valid=false;
        }
    }
    if(requestPermissions.size()>0){
        ActivityCompat.requestPermissions(this,requestPermissions.toArray(new String[requestPermissions.size()]),REQUEST_CODE_PERMISSION);
    }
    return valid;
}
}