微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

布局文件main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  android:orientation="vertical" 
  tools:ignore="HardcodedText" > 
  <Button 
    android:id="@+id/bt_getCantacts" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="获取联系人信息" /> 
</LinearLayout> 

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,"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<ContactBean> list = (ArrayList<ContactBean>) 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<Cursor,Void,ArrayList<ContactBean>> { 
  /** 开始整理 */ 
  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<ContactBean> doInCursor... params) { 
    // 只需要把原来放在子线程的代码放到这个方法就行 
    Cursor cursor = params[0]; 
    ArrayList<ContactBean> ciList = new ArrayList<ContactBean>(); 
    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<ContactBean> 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<ContactBean> result) { 
    Message message = new Message(); 
    message.what = messageWhat; 
    Bundle bundle = new Bundle(); 
    bundle.putSerializable("完成",result); 
    message.setData(bundle); 
    if (mHandler != null) { 
      mHandler.sendMessage(message); 
    } 
  } 
} 

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐