How can I check if startActivity() will fail with SecurityException due to lack of permission?

浪子不回头ぞ 提交于 2019-12-10 21:44:13

问题


I want to support adding Contacts with the Contact Picker. It appears that the READ_CONTACTS permission is required in certain phones and not others - see Do contact picker queries require the read_contacts permission depending on the android version?

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

The exception occurs in onActivityResult() when I query the returned data (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();
                                }
                       }
              }
     }

I want to know how I can check beforehand if startActivity will fail, so I can disable the functionality before having to do this "live check".

Tried this as a possible solution, but did not work as ai.permission is always null:

    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;

来源:https://stackoverflow.com/questions/11602641/how-can-i-check-if-startactivity-will-fail-with-securityexception-due-to-lack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!