android6.0动态申请权限的方法

private final int CAMERA_REQUEST_CODE=1;
private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
                new AlertDialog.Builder(this)
                        .setMessage("申请相机权限")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(DragTopActivity.this,
                                        new String[]{Manifest.permission.READ_PHONE_STATE}, CAMERA_REQUEST_CODE);
                            }
                        })
                        .show();
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_PHONE_STATE}, CAMERA_REQUEST_CODE);
            }
        } else {
        }
    }

以下是郭霖大神动态申请权限的代码:
public class MainActivity extends AppCompatActivity {
    private Button button;

    @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&&grantResults[0]==PackageManager.PERMISSION_GRANTED)//grant是同意的意思,grantResults这个参数中放的是0或者是1,0表示同意,1表示禁止
                {
                    Toast.makeText(MainActivity.this,"已经有权限了",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this,"请先申请权限",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED)//checkSelfPermission返回的结果如果是0表示同意,1表示禁止
                {
                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CALL_PHONE},1);//当调用requestPermissions时,系统会自动创建一个对话框
                }else {

                }
            }
        });

    }
}

你可能感兴趣的:(android6.0动态申请权限的方法)