READ_CONTACTS权限不起作用

时间:2018-04-11 01:52:45

标签: java android android-studio

当我在我的模拟器中运行以下代码时,它会给出以下消息:  “该应用已停止”

我正在尝试阅读联系人并创建一个显示联系人的列表视图,并允许用户选择他们的紧急联系人。

这是我的代码:

public class ContactsActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    final int REQUEST_READ_CONTACTS = 123;
    MyAdapter madapt;
    ArrayList<String> store = new ArrayList<String>();
    String s1, s2, s3, s4;
    String newline = "\n";
    Button b;
    CheckBox cb;
    FileOutputStream out1;
    List<String> name1 = new ArrayList<String>();
    List<String> phone1 = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        AlertDialog.Builder alert = new AlertDialog.Builder(this);


        alert.setNegativeButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        })
                .setMessage("This App requires GPS to work properly. Please keep the GPS enabled whenever you are using this App.")
                .show();

        getContacts(this.getContentResolver());
        ListView lv = (ListView) findViewById(R.id.lv);
        madapt = new MyAdapter();
        lv.setAdapter(madapt);
        lv.setOnItemClickListener(this);
        lv.setItemsCanFocus(false);
        lv.setTextFilterEnabled(true);
        b = (Button) findViewById(R.id.button);


        File file = new File(getFilesDir(), "contacts");
        try {
            out1 = openFileOutput("contacts", Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
        }

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (!store.isEmpty()) {
                    for (String s : store) {
                        s1 = s.replace("(", "");
                        s2 = s1.replace(")", "");
                        s3 = s2.replace(" ", "");
                        s4 = s3.replace("-", "");
                        try {
                            out1.write(s4.getBytes());
                            out1.write(newline.getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        //TODO: Get intent to work

                        Intent sendstoredcontacts = new Intent(ContactsActivity.this, FirstActivity.class);
                        sendstoredcontacts.putStringArrayListExtra("CONTACTS", store); // getText() SHOULD NOT be static!!!
                        startActivity(sendstoredcontacts);
                    }
                } else {
                    Toast.makeText(ContactsActivity.this, "At least 1 Contact must be selected !", Toast.LENGTH_SHORT).show();
                }


            }
        });
    }


    private void getContacts(ContentResolver cr) {

        Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

        while (phones.moveToNext()) {
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            System.out.println(".................." + phoneNumber);
            name1.add(name);
            phone1.add(phoneNumber);

        }

        phones.close();
    }

    public void askForContactPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                if (ContextCompat.checkSelfPermission(ContactsActivity.this,
                        Manifest.permission.READ_CONTACTS)
                        != PackageManager.PERMISSION_GRANTED) {

                    // Permission is not granted
                    // Should we show an explanation?
                    if (ActivityCompat.shouldShowRequestPermissionRationale(ContactsActivity.this,
                            Manifest.permission.READ_CONTACTS)) {

                        // Show an explanation to the user *asynchronously* -- don't block
                        // this thread waiting for the user's response! After the user
                        // sees the explanation, try again to request the permission.

                    } else {

                        // No explanation needed; request the permission
                        ActivityCompat.requestPermissions(ContactsActivity.this,
                                new String[]{Manifest.permission.READ_CONTACTS},
                                REQUEST_READ_CONTACTS);

                        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                        // app-defined int constant. The callback method gets the
                        // result of the request.
                    }
                } else {
                    // Permission has already been granted
                }
            }
        }



    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }

    class MyAdapter extends BaseAdapter {
        LayoutInflater inf;

        MyAdapter() {
            inf = (LayoutInflater) ContactsActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return name1.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            // if(convertView!=null)
            vi = inf.inflate(R.layout.row, null);

            TextView tv = (TextView) vi.findViewById(R.id.tv);
            TextView textView = (TextView) vi.findViewById(R.id.textView);
            cb = (CheckBox) vi.findViewById(R.id.checkBox);
            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                    if (isChecked) {

                        store.add(phone1.get(position));

                    } else {
                        store.remove(phone1.get(position));
                    }
                }
            });
            tv.setText("Name: " + name1.get(position));
            textView.setText("Number: " + phone1.get(position));
            return vi;
        }


    }
    private boolean checkPermission(String permission) {
        int checkPermission = ContextCompat.checkSelfPermission(this, permission);
        return (checkPermission == PackageManager.PERMISSION_GRANTED);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_READ_CONTACTS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request.
        }
    }
}

这是我的崩溃日志:

致命的例外:主要                                                                             过程:com.example.android.vigilant,PID:2498                                                                             java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.android.vigilant / com.example.android.vigilant.ContactsActivity}:java.lang.SecurityException:权限拒绝:打开提供程序com ProcessRecord中的.android.providers.contacts.ContactsProvider2 {df95360 2498:com.example.android.vigilant / u0a77}(pid = 2498,uid = 10077)需要android.permission.READ_CONTACTS

*编辑: 同样在我的清单文件中,我有:

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

我如何启用我的权限工作?如何使用代码/我将特定代码添加到当前代码中来实现此代码?

我有API 25

2 个答案:

答案 0 :(得分:0)

您仍需要在清单中添加权限

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

答案 1 :(得分:0)

你什么时候打电话给你的许可方法?

通过以下方式更新您的权限方法。

public boolean checkAndAskForContactPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(ContactsActivity.this,
                Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(ContactsActivity.this,
                    Manifest.permission.READ_CONTACTS)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
            } else {
                // No explanation needed; request the permission
                ActivityCompat.requestPermissions(ContactsActivity.this,
                        new String[]{Manifest.permission.READ_CONTACTS},
                        REQUEST_READ_CONTACTS);
                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            return true;
            // Permission has already been granted
        }
    } else return true;
}

并在onCreate()之后调用此方法,如

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
     if (!checkAndAskForContactPermission()) return;
... your stuff here
}

如果有任何其他问题,请告诉我。