简单的AsyncQueryHandler获取手机联系人
程序员文章站
2022-05-15 21:20:30
...
利用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, 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<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); } } }
小工具,供人参考,方便广大程序员,欢迎指正。