Android中擷取系統通訊錄連絡人並顯示在EditText

來源:互聯網
上載者:User

        好多時候,我們都要使用選擇連絡人的操作,自己寫的話 很麻煩,倒不如直接調用系統的通訊錄,這樣來的直接,來的方便

       下面我們來看需求:

 

需求:
一個EditText 點擊button的時候轉到系統通訊錄,選中其中一個通訊錄item返回當前介面且把
選中的連絡人號碼使用者名稱顯示在EditText 上。

 

 

直接上代碼:

import android.app.Activity;import android.content.ContentResolver;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.ContactsContract;import android.view.View;import android.widget.EditText;public class MainActivity extends Activity {    EditText text;    String username,usernumber;        @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        text = (EditText)findViewById(R.id.number);    }       public void click(View v){       startActivityForResult(new Intent(                Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI), 0);   }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (resultCode == Activity.RESULT_OK) {            ContentResolver reContentResolverol = getContentResolver();             Uri contactData = data.getData();             @SuppressWarnings("deprecation")            Cursor cursor = managedQuery(contactData, null, null, null, null);             cursor.moveToFirst();             username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));            Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,                      null,                      ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,                      null,                      null);             while (phone.moveToNext()) {                 usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));                 text.setText(usernumber+" ("+username+")");             }         }    }}

 

需要添加許可權:

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.