您好,登錄后才能下訂單哦!
利用AsyncQueryHandler能異步任務獲取手機聯(lián)系人,增加用戶體驗,使用起來也很方便。不多說,上干貨。
布局文件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="獲取聯(lián)系人信息" /> </LinearLayout>
contact.java 聯(lián)系人bean文件
package com.larson.cantact; public class Contact { private int contactId;//聯(lián)系人ID private String displayName;//聯(lián)系人姓名 private String phoneNum;//聯(lián)系人手機號 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() { // 聯(lián)系人URI Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 聯(lián)系人ID,聯(lián)系人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); } /** * 發(fā)送開始整理消息 * * @param messageWhat */ private void sendStartMessage(int messageWhat) { Message message = new Message(); message.what = messageWhat; if (mHandler != null) { mHandler.sendMessage(message); } } /** * 發(fā)送整理結束消息 * * @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); } } }
小工具,供人參考,方便廣大程序員,歡迎指正。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。