Android 查询具有给定电子邮件 ID 的电子邮件

Android query for email with given email id

我让用户从具有以下意图的联系人中选择电子邮件:

Intent emailPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Email.CONTENT_URI);
startActivityForResult(emailPickerIntent, Constants.CONTACT_PICKER_RESULT);

如何查询用户在 onActivityResult 方法中选择的邮箱?

以下代码将帮助您在 ActivityResult 上获取电子邮件地址:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if (resultCode == RESULT_OK) {
        switch (requestCode) 
        {
        case CONTACT_PICKER_RESULT:
            Cursor cursor = null;
            String email = "", name = "";
            try {
                Uri result = data.getData();
                Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());

                // get the contact id from the Uri
                String id = result.getLastPathSegment();

                // query for everything email
                cursor = getContentResolver().query(Email.CONTENT_URI,  null, Email._ID + "=" + id, null, null);

                int nameId = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
                int emailIdx = cursor.getColumnIndex(Email.DATA);

                // let's just get the first email
                if (cursor.moveToFirst()) {
                    email = cursor.getString(emailIdx);
                    name = cursor.getString(nameId);
                    Log.v(DEBUG_TAG, "Got email: " + email);
                } else {
                    Log.w(DEBUG_TAG, "No results");
                }
            } catch (Exception e) {
                Log.e(DEBUG_TAG, "Failed to get email data", e);
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
                EditText emailEntry = (EditText) findViewById(R.id.editTextv);
                EditText personEntry = (EditText) findViewById(R.id.person);
                emailEntry.setText(email);
                personEntry.setText(name);
                if (email.length() == 0 && name.length() == 0) 
                {
                    Toast.makeText(this, "No Email for Selected Contact",Toast.LENGTH_LONG).show();
                }
            }
            break;
        }

    } else {
        Log.w(DEBUG_TAG, "Warning: activity result not ok");
    }
}
}

您还必须在清单文件中添加以下权限:

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