Android使用AsyncQueryHandler实现获取手机联系人功能

利用AsyncQueryHandler能异步任务获取手机联系人,增加用户体验,使用起来也很方便。不多说,上干货。

10年积累的网站制作、网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有青羊免费网站建设让你可以放心的选择与我们合作。

布局文件main.xml

<?xml version="1.0" encoding="utf-8"?> 
 
  

contact.java 联系人bean文件

package com.larson.cantact; 
public class Contact { 
  private int contactId;//联系人ID 
  private String displayName;//联系人姓名 
  private String phoneNum;//联系人手机号 
  private String sortKey;//排序Key 
  private Long photoId;//头像ID 
  private String lookUpKey; 
  private int selected = 0;//被选中的行号 
  private String formattedNumber;//被格式化的号码 
  private String pinyin;//姓名对应的汉语拼音 
                                                                                              
  public int getContactId() { 
    return contactId; 
  } 
  public void setContactId(int contactId) { 
    this.contactId = contactId; 
  } 
  public String getDisplayName() { 
    return displayName; 
  } 
  public void setDisplayName(String displayName) { 
    this.displayName = displayName; 
  } 
  public String getPhoneNum() { 
    return phoneNum; 
  } 
  public void setPhoneNum(String phoneNum) { 
    this.phoneNum = phoneNum; 
  } 
  public String getSortKey() { 
    return sortKey; 
  } 
  public void setSortKey(String sortKey) { 
    this.sortKey = sortKey; 
  } 
  public Long getPhotoId() { 
    return photoId; 
  } 
  public void setPhotoId(Long photoId) { 
    this.photoId = photoId; 
  } 
  public String getLookUpKey() { 
    return lookUpKey; 
  } 
  public void setLookUpKey(String lookUpKey) { 
    this.lookUpKey = lookUpKey; 
  } 
  public int getSelected() { 
    return selected; 
  } 
  public void setSelected(int selected) { 
    this.selected = selected; 
  } 
  public String getFormattedNumber() { 
    return formattedNumber; 
  } 
  public void setFormattedNumber(String formattedNumber) { 
    this.formattedNumber = formattedNumber; 
  } 
  public String getPinyin() { 
    return pinyin; 
  } 
  public void setPinyin(String pinyin) { 
    this.pinyin = pinyin; 
  } 
} 

MainActivity.java

package com.larson.cantact; 
import java.util.ArrayList; 
import android.app.Activity; 
import android.content.AsyncQueryHandler; 
import android.content.ContentResolver; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.provider.ContactsContract; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
public class MainActivity extends Activity { 
  private Button myCantacts; 
  private AsyncQueryHandler asyncQuery; 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    myCantacts = (Button) this.findViewById(R.id.bt_getCantacts); 
    myCantacts.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        asyncQuery = new MyAsyncQueryHandler(getContentResolver()); 
        initSQL(); 
      } 
    }); 
  } 
  protected void initSQL() { 
    // 联系人URI 
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 
    // 联系人ID,联系人NAME, 
    String[] projection = { ContactsContract.CommonDataKinds.Phone._ID, 
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, 
        ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key", 
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID, }; 
    asyncQuery.startQuery(0, null, uri, projection, null, null, 
        "sort_key COLLATE LOCALIZED asc"); 
  } 
  private class MyAsyncQueryHandler extends AsyncQueryHandler { 
    public MyAsyncQueryHandler(ContentResolver cr) { 
      super(cr); 
    } 
    protected void onQueryComplete(int token, Object cookie, Cursor cursor) { 
      querying(cursor); 
    } 
  } 
  private void querying(final Cursor cursor) { 
    Handler handlerInsertOrder = new Handler() { 
      public void handleMessage(Message msg) { 
        switch (msg.what) { 
        case MyAsyncTask.DOWNLOADING_START_MESSAGE: 
          System.out.println("begin to sort out t9"); 
          break; 
        case MyAsyncTask.DOWNLOAD_END_MESSAGE: 
          Bundle bundle1 = msg.getData(); 
          ArrayList list = (ArrayList) bundle1 
              .get("完成"); 
          for (ContactBean ci : list) { 
            System.out.println(ci.getDisplayName()); 
            System.out.println(ci.getPhoneNum()); 
            System.out.println("--------------------------------"); 
          } 
          break; 
        default: 
          break; 
        } 
        super.handleMessage(msg); 
      } 
    }; 
    MyAsyncTask.startRequestServerData(this, handlerInsertOrder, cursor); 
  } 
} 

自定义的MyAsyncTask.java

package com.anjoyo.cantact; 
import java.util.ArrayList; 
import android.content.Context; 
import android.database.Cursor; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
public class MyAsyncTask extends 
    AsyncTask> { 
  /** 开始整理 */ 
  public static final int DOWNLOADING_START_MESSAGE = 7; 
  /** 整理结束 */ 
  public static final int DOWNLOAD_END_MESSAGE = 17; 
  private Context mContext = null; 
  private Handler mHandler = null; 
  protected MyAsyncTask(Context context, Handler handler) { 
    this.mContext = context; 
    this.mHandler = handler; 
  } 
  @Override 
  protected void onPreExecute() { 
    sendStartMessage(DOWNLOADING_START_MESSAGE); 
  } 
  @Override 
  protected ArrayList doInCursor... params) { 
    // 只需要把原来放在子线程的代码放到这个方法就行 
    Cursor cursor = params[0]; 
    ArrayList ciList = new ArrayList(); 
    if (cursor != null && cursor.getCount() > 0) { 
      try { 
        cursor.moveToFirst(); 
        for (int i = 0; i < cursor.getCount(); i++) { 
          cursor.moveToPosition(i); 
          String name = cursor.getString(1); 
          String number = cursor.getString(2); 
          int contactId = cursor.getInt(4); 
          ContactBean contactInfo = new ContactBean(); 
          contactInfo.setContactId(contactId); 
          contactInfo.setPhoneNum(number); 
          contactInfo.setDisplayName(name); 
          if (contactInfo.getDisplayName() == null) { 
            contactInfo.setDisplayName(contactInfo.getPhoneNum()); 
          } 
                                             
          ciList.add(contactInfo); 
        } 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
    return ciList; 
  } 
  @Override 
  protected void onPostExecute(ArrayList result) { 
    sendEndMessage(DOWNLOAD_END_MESSAGE, result); 
  } 
  public static void startRequestServerData(Context context, Handler handler, 
      Cursor cursor) { 
    new MyAsyncTask(context, handler).execute(cursor); 
  } 
  /** 
   * 发送开始整理消息 
   * 
   * @param messageWhat 
   */ 
  private void sendStartMessage(int messageWhat) { 
    Message message = new Message(); 
    message.what = messageWhat; 
    if (mHandler != null) { 
      mHandler.sendMessage(message); 
    } 
  } 
  /** 
   * 发送整理结束消息 
   * 
   * @param messageWhat 
   */ 
  private void sendEndMessage(int messageWhat, ArrayList result) { 
    Message message = new Message(); 
    message.what = messageWhat; 
    Bundle bundle = new Bundle(); 
    bundle.putSerializable("完成", result); 
    message.setData(bundle); 
    if (mHandler != null) { 
      mHandler.sendMessage(message); 
    } 
  } 
} 

 小工具,供人参考,方便广大程序员,欢迎指正。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


文章标题:Android使用AsyncQueryHandler实现获取手机联系人功能
标题链接:http://azwzsj.com/article/iiigoo.html