1. 程式人生 > >跳轉到通訊錄聯絡人獲取資訊

跳轉到通訊錄聯絡人獲取資訊

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * 獲取通訊錄聯絡人資訊(姓名+電話號碼)
 */
public class MainActivity extends AppCompatActivity {


    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        text = findViewById(R.id.text);


        Button goto_contact = findViewById(R.id.goto_contact);
        goto_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri = ContactsContract.Contacts.CONTENT_URI;
                Intent intent = new Intent(Intent.ACTION_PICK,uri);
                startActivityForResult(intent,0);
            }
        });
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0) {
                Uri uri=data.getData();
                String[] contacts=getPhone(uri);
                text.setText("姓名:"+contacts[0]+" "+"手機號:"+contacts[1]);
            }
        }
    }



    private String[] getPhone(Uri uri){
        String[] contact=new String[2];
        
        ContentResolver cr = getContentResolver();
        //取得電話本游標
        Cursor cursor=cr.query(uri,null,null,null,null);
        if(cursor!=null){
            cursor.moveToFirst();
            //獲取聯絡人姓名
            int nameFieldColumnIndex=cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0]=cursor.getString(nameFieldColumnIndex);
            //獲取電話號碼
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if(phone != null){
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        }
        else{
            return null;
        }
        return contact;
    }
}

清單檔案中記得加上

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

否則報錯或者程式崩潰,android 6.0及以上需動態加此許可權。