編輯:關於 Android 程式設計
在這個系列的前兩篇文章裡,我們已經分別談過如何取得手機裡的聯絡人以及通話紀錄。到了第三篇,終於要來啃最硬的一塊骨頭——短信。之所以說它是通訊管理中的難點,是因為短信同時牽涉到「短信會話」與「短信詳情」兩個層次,加上實際裝置上的短信資料量往往相當龐大,如果處理不當很容易造成卡頓。
因此本篇會帶大家用 AsyncQueryHandler 這個非同步查詢框架來讀取資料,並搭配 CursorAdapter 完成資料與畫面的綁定,讓整個列表滾動起來依然順暢。


值得一提的是,在短信列表裡我們還能順手把聯絡人的頭像與姓名抓出來顯示。這個邏輯已經封裝在工具類中:若通訊錄裡找得到對方,就顯示姓名與頭像;找不到則退回顯示號碼與預設頭像。這套做法其實在聯絡人與通話紀錄頁面也能通用,有興趣動手改寫的朋友不妨自己試試。
package cn.zxw.contact.utils; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.database.Cursor; import android.support.v4.widget.CursorAdapter; import android.util.Log; /** * QueryHandler框架 * @author zhan * */ public class QueryHandler extends AsyncQueryHandler { private static final String TAG = QueryHandler; public QueryHandler(ContentResolver cr) { super(cr); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { super.onQueryComplete(token, cookie, cursor); String names[] = cursor.getColumnNames(); for (String name : names) { Log.i(TAG, name); } // 查詢完成 // if (cookie != null && cookie instanceof CursorAdapter) { // 把查詢出來的cursor結果設置給adapter CursorAdapter adapter = (CursorAdapter) cookie; adapter.changeCursor(cursor); } } }
package cn.zxw.contact; import cn.zxw.contact.utils.ContactsUtils; import cn.zxw.contact.utils.QueryHandler; import cn.zxw.contact.utils.TimeUtils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.widget.CursorAdapter; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; /** * 短信列表 * 點擊短息列表中的條目會進入條目對應的短信詳情頁面 * @author zhan * */ public class MsgActivity extends Activity implements OnItemClickListener { private ListView lv; public MyCursorAdapter adapter; // 查詢的結果集 private String[] projection = new String[] { snippet, sms.thread_id as _id, msg_count, sms.address as address, sms.date as date }; private final static int SINPPET_COLUMN_INDEX = 0; private final static int THREAD_ID_COLUMN_INDEX = 1; private final static int MSG_COUNT_COLUMN_INDEX = 2; private final static int ADDRESS_COLUMN_INDEX = 3; private final static int DATE_COLUMN_INDEX = 4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contacts_msg_calllog); lv = (ListView) findViewById(R.id.lv); adapter=new MyCursorAdapter(this, null);//初始化Adapter lv.setAdapter(adapter); startQuery(); lv.setOnItemClickListener(this); } /** * 執行查詢 */ private void startQuery() { QueryHandler mQueryHandler = new QueryHandler(getContentResolver()); // 執行查詢 /** * token唯一標識 cookie可以用來傳遞數據 上面的參數會傳遞給一個方法 onQueryComplete */ Uri uri = Uri.parse(content://sms/conversations); // mQueryHandler.startQuery(0, null, uri, projection, null, // null,date desc); mQueryHandler.startQuery(0, adapter, uri, projection, null, null, date desc); } // 自定義CursorAdapter private class MyCursorAdapter extends CursorAdapter { private LayoutInflater mInflater; public MyCursorAdapter(Context context, Cursor c) { super(context, c); mInflater = LayoutInflater.from(context); } // 創建條目 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.activity_msg_list_item, null); return view; } // 綁定條目 @Override public void bindView(View view, Context context, Cursor cursor) { ImageView iv_header = (ImageView) view.findViewById(R.id.iv_header); TextView tv_number = (TextView) view.findViewById(R.id.tv_number); TextView tv_body = (TextView) view.findViewById(R.id.tv_body); TextView tv_date = (TextView) view.findViewById(R.id.tv_date); int id = cursor.getInt(THREAD_ID_COLUMN_INDEX); String address = cursor.getString(ADDRESS_COLUMN_INDEX); int msg_count = cursor.getInt(MSG_COUNT_COLUMN_INDEX); long date = cursor.getLong(DATE_COLUMN_INDEX); String body = cursor.getString(SINPPET_COLUMN_INDEX); System.out.println(address); String displayName = ContactsUtils.getContactNameByAddress( getApplicationContext(), address); if (TextUtils.isEmpty(displayName)) { iv_header.setImageResource(R.drawable.ic_launcher); tv_number.setText(address + ( + msg_count + )); } else { tv_number.setText(displayName + ( + msg_count + )); Bitmap bitmap = ContactsUtils.getContactPhotoByAddress( getApplicationContext(), address); if (bitmap == null) { iv_header.setImageResource(R.drawable.ic_launcher); } else { iv_header.setImageBitmap(bitmap); } } tv_body.setText(body); String dataStr = TimeUtils .formatDate(getApplicationContext(), date); tv_date.setText(dataStr); } } @Override public void onItemClick(AdapterView parent, View view, int position, long id) { //傳遞數據 Cursor cursor = (Cursor) adapter.getItem(position); int _id = cursor.getInt(THREAD_ID_COLUMN_INDEX); String address=cursor.getString(ADDRESS_COLUMN_INDEX); String displayName=ContactsUtils.getContactNameByAddress(getApplicationContext(), address); //進入列表詳情頁面 Intent intent=new Intent(this, MsgDetailActivity.class); intent.putExtra(_id, _id); intent.putExtra(address, address); intent.putExtra(displayName, displayName); startActivity(intent); } }
點擊會話列表中的任一條目後,便會跳轉到對應的短信詳情頁,而在這個頁面裡我們也能直接進行短信的發送。
package cn.zxw.contact; import cn.zxw.contact.utils.Constants; import cn.zxw.contact.utils.ContactsMsgUtils; import cn.zxw.contact.utils.QueryHandler; import cn.zxw.contact.utils.TimeUtils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.widget.CursorAdapter; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MsgDetailActivity extends Activity implements OnClickListener { private Button bt_back; private TextView tv_number; private ListView lv; private EditText et_msg_content; private Button bt_send; private int _id; private String address; private MyCursorAdapter adapter; private String[] projection=new String[]{ _id,type,body,date }; private final static int ID_COLUMN_INDEX=0; private final static int TYPE_COLUMN_INDEX=1; private final static int BODY_COLUMN_INDEX=2; private final static int DATE_COLUMN_INDEX=3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_msg_list_detail); initView(); startQuery(); } public void initView() { bt_back = (Button) findViewById(R.id.bt_back); tv_number = (TextView) findViewById(R.id.tv_number); lv = (ListView) findViewById(R.id.lv); et_msg_content = (EditText) findViewById(R.id.et_msg_content); bt_send = (Button) findViewById(R.id.bt_send); bt_back.setOnClickListener(this); bt_send.setOnClickListener(this); Intent intent=getIntent(); _id = intent.getIntExtra(_id, 0); address = intent.getStringExtra(address); String displayName=intent.getStringExtra(displayName); if (TextUtils.isEmpty(displayName)) { tv_number.setText(address); }else{ tv_number.setText(displayName); } adapter = new MyCursorAdapter(this, null); lv.setAdapter(adapter); } public void startQuery() { QueryHandler mHandler=new QueryHandler(getContentResolver()); String selection=thread_id=?; String[] selectionArgs=new String[]{_id+}; mHandler.startQuery(0, adapter, Constants.SMS_URI, projection, selection, selectionArgs, date asc); } private class MyCursorAdapter extends CursorAdapter{ public MyCursorAdapter(Context context, Cursor c) { super(context, c); } @Override public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { View view=getLayoutInflater().inflate(R.layout.activity_msg_detial_item, null); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { TextView tv_date=(TextView) view.findViewById(R.id.tv_date); TextView tv_send=(TextView) view.findViewById(R.id.tv_send); TextView tv_receive=(TextView) view.findViewById(R.id.tv_receive); long date=cursor.getLong(DATE_COLUMN_INDEX); String body=cursor.getString(BODY_COLUMN_INDEX); int type=cursor.getInt(TYPE_COLUMN_INDEX); String str=TimeUtils.formatDate(getApplicationContext(), date); tv_date.setText(str); if (type==Constants.RECEIVE_TYPE) { tv_date.setVisibility(View.VISIBLE); tv_receive.setText(body); tv_send.setVisibility(View.GONE); }else if (type==Constants.SEND_TYPE) { tv_date.setVisibility(View.VISIBLE); tv_send.setVisibility(View.VISIBLE); tv_send.setText(body); tv_receive.setVisibility(View.GONE); } } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); lv.setSelection(adapter.getCount()-1); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.bt_back: finish(); break; case R.id.bt_send: String content=et_msg_content.getText().toString().trim(); if (TextUtils.isEmpty(content)) { Toast.makeText(getApplicationContext(), 短信為空, 0).show(); }else{ ContactsMsgUtils.sendMsg(getApplicationContext(), address, content); et_msg_content.setText(); } break; default: break; } } }
最後是真正負責把短信送出去的方法。這裡要注意的是,當內容過長時必須先拆分,再交由 SmsManager 分批送出,同時別忘了手動把這筆訊息寫回資料庫,這樣使用者才會在自己的對話裡看到它。
/** * 發送短信 * @param address * @param content */ public static void sendMsg(Context context,String address,String content){ SmsManager smsManager=SmsManager.getDefault();//如果短信太長,拆分短信 ArrayList parts=smsManager.divideMessage(content); smsManager.sendMultipartTextMessage(address, null, parts, null, null); //手動存儲短信 ContentResolver resolver=context.getContentResolver(); Uri uri=Constants.SMS_URI; ContentValues values=new ContentValues(); values.put(address, address); values.put(body, content); values.put(type, Constants.SEND_TYPE); values.put(date, System.currentTimeMillis()); resolver.insert(uri, values); }
整體串連下來,短信的讀取、展示與發送就都齊備了。實作時還需要記得在清單檔中聲明讀寫短信的權限,否則查詢會失敗。
greenDAO 上手實戰:從配置、代碼生成到增刪改查全流程
最近項目裡用到了 greenDAO,順手把整個使用過程記錄下來。 一、greenDAO 是什麼 greenDAO 是對 SQLite 的封裝,讓我們能更省心地把玩 SQ
Android 拍照與相冊選圖,含圖片裁剪完整實作
幾乎每個有註冊功能的 App 都需要「設定頭像」。這個看似簡單的功能,背後其實牽涉到相機啟動、相冊挑選、URI 取得、以及裁剪後的結果回傳。今天就把這套常用模組完整記錄下
Android 4.2.2 Stagefright 中的 A31 OMX 插件與 Codec 組件構建全解析
本文是閱讀源碼過程中的點滴記錄,轉載請注明出處。上一篇提到 AwesomePlayer::onPrepareAsyncEvent() 開始獲取並創建解碼器組件,這裡把這個
用frame動畫打造 Android 蝸牛風格進度條
好的介面細節能顯著提升使用者的第一印象。本文實作一個以蝸牛爬行動畫作為「滑塊」的進度條,讓等待過程更有趣味性。 一、準備frame動畫資源 <?xml versi