requestPermissions() 没有响应,当我点击按钮时什么也没有发生

时间:2021-03-18 16:22:06

标签: android

这是我的代码,我像文档说的那样写。 但是当我点击按钮时什么也没有发生。 只有按摩节目:“D/CompatibilityChangeReporter:Compat change id报告:147798919;UID 10155;状态:ENABLED”

Button bt_show_contacts_list=findViewById(R.id.button_show_contacts_list);
        bt_show_contacts_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS)==
                        PackageManager.PERMISSION_GRANTED){
                    // You can use the API that requires the permission
                    start();
                }else if(shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)){
                    Toast.makeText(getBaseContext(),"it's important , you are suppose to allow the permission",Toast.LENGTH_LONG).show();
                }else{
                    requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},1);
                }
            }
        });

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //Application specific request code to match with a result reported to TODO

        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    start();
                }else{
                    Toast.makeText(getBaseContext(),"go to setting , otherwise you can't use this",Toast.LENGTH_LONG).show();
                }
                return;
        }

    }
    public void start(){
        Toast.makeText(getBaseContext(),"start",Toast.LENGTH_LONG).show();
    }

1 个答案:

答案 0 :(得分:1)

你需要在AndroidManifest.xml中添加这段代码,然后代码就会出现。

 <uses-permission android:name="android.permission.READ_CONTACTS"/>