How to call Android contacts list?

前端 未结 13 2261
傲寒
傲寒 2020-11-22 02:50

I\'m making an Android app, and need to call the phone\'s contact list. I need to call the contacts list function, pick a contact, then return to my app with the contact\'s

13条回答
  •  孤城傲影
    2020-11-22 03:29

    I use the code provided by @Colin MacKenzie - III. Thanks a lot!

    For someone who are looking for a replacement of 'deprecated' managedQuery:

    1st, assuming using v4 support lib:

    import android.support.v4.app.LoaderManager;
    import android.support.v4.content.CursorLoader;
    import android.support.v4.content.Loader;
    

    2nd:

    your_(activity)_class implements LoaderManager.LoaderCallbacks
    

    3rd,

    // temporarily store the 'data.getData()' from onActivityResult
    private Uri tmp_url;
    

    4th, override callbacks:

    @Override
    public Loader onCreateLoader(int id, Bundle args) {
        // create the loader here!
        CursorLoader cursorLoader = new CursorLoader(this, tmp_url, null, null, null, null);
        return cursorLoader;
    }
    
    @Override
    public void onLoadFinished(Loader loader, Cursor cursor) {
        getContactInfo(cursor); // here it is!
    }
    
    @Override
    public void onLoaderReset(Loader loader) {
    }
    

    5th:

    public void initLoader(Uri data){
        // will be used in onCreateLoader callback
        this.tmp_url = data;
        // 'this' is an Activity instance, implementing those callbacks
        this.getSupportLoaderManager().initLoader(0, null, this);
    }
    

    6th, the code above, except that I change the signature param from Intent to Cursor:

    protected void getContactInfo(Cursor cursor)
    {
    
       // Cursor cursor =  managedQuery(intent.getData(), null, null, null, null);      
       while (cursor.moveToNext()) 
       {
            // same above ...
       } 
    

    7th, call initLoader:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (PICK_CONTACT == requestCode) {
            this.initLoader(data.getData(), this);
        }
    }
    

    8th, don't forget this piece of code

        Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        this.act.startActivityForResult(intentContact, PICK_CONTACT);
    

    References:

    Android Fundamentals: Properly Loading Data

    Initializing a Loader in an Activity

提交回复
热议问题