我如何检查是否startActivity()将抛出:SecurityException失败是由于缺少

2019-09-20 01:02发布

我想支持添加与联络人选取联系人。 看来,READ_CONTACTS许可在特定的手机,而不是其他必需的-见做联系人挑选查询需要取决于Android版本的read_contacts许可?

    Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
    startActivityForResult(intent, CHOOSE_CONTACT);

发生在onActivityResult()的异常,当我查询返回的数据(mangedQUery())

     if (resultCode == Activity.RESULT_OK) {
              Uri contactData = data.getData();
              if (contactData != null) {
                       Cursor mCursor =  managedQuery(contactData, null, null, null, null);
                       if (mCursor != null && mCursor.moveToFirst()) {
                                long id = mCursor.getLong(mCursor.getColumnIndex(People._ID));
                                String name = mCursor.getString(mCursor.getColumnIndex(People.DISPLAY_NAME));

                                if (name != null) {
                                         displayName(name);
                                         _contact_id = id;
                                         _contact_name = name.trim();
                                }
                       }
              }
     }

我想知道我怎么能事先检查startActivity会失败,所以不得不这样做“现场检查”之前,我可以禁用该功能。

试图将此作为一个可能的解决方案,但由于ai.permission没有工作总是空:

    final PackageManager packageManager = getPackageManager();
    final Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

    for (ResolveInfo resolve : list) {
        ActivityInfo ai = resolve.activityInfo;
        if (ai.permission != null) {
            return false;
        }
    }

    return true;
文章来源: How can I check if startActivity() will fail with SecurityException due to lack of permission?