編輯:關於 Android 程式設計
本文以完整實例,示範如何在 Android 中讀取手機聯絡人、撥打電話、傳送簡訊,並搭配長按彈出 ContextMenu 選單,供大家參考。
1. 專案結構如下圖,主要會操作紅色框內的檔案。

2. 先來看版面配置。
a. main.xml:程式運行的主介面,主要用 ListView 列表控件展示手機聯絡人。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg" android:orientation="vertical" > <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginLeft="5dip" android:cacheColorHint="#00000000" android:divider="@drawable/divider_horizontal_bright" android:paddingRight="5dip" > </ListView> </LinearLayout>
b. list_item.xml:ListView 的列表項版面,相當於展示用的範本。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:id="@+id/imgView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/photo" android:paddingRight="2dip" /> <TextView android:id="@+id/name" android:layout_width="80dip" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:paddingTop="8dip" android:singleLine="false" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#ffffff" /> <TextView android:id="@+id/number" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginRight="6dip" android:paddingTop="8dip" android:singleLine="false" android:textColor="#ffffff" android:textAppearance="?android:attr/textAppearanceMedium"/> </LinearLayout>
c. phonedetails.xml:長按選單顯示聯絡人詳細資料的版面,示範中僅做了跳轉展示。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/ymw" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium"/> </LinearLayout>
3. Java 實作程式碼如下。
a. MainActivity.java:程式運行的入口檔。
package com.example.myandroid; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.ymw.details.Detail; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ListView listView = (ListView) findViewById(R.id.listView); // 生成動態數組,加入數據 ArrayList<HashMap<String, Object>> listItem = fillMaps(); SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem, R.layout.list_item, new String[] { "imgView", "name", "number" }, new int[] { R.id.imgView, R.id.name, R.id.number }); listView.setAdapter(listItemAdapter); // 添加單擊事件 listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { HashMap<String, String> map = (HashMap<String, String>) listView .getItemAtPosition(arg2); String name = map.get("name"); Toast toast = Toast.makeText(getApplicationContext(), "第" + arg2 + "項" + name, Toast.LENGTH_LONG); toast.show(); String phoneNum = map.get("number"); Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNum)); startActivity(intent); } }); // 添加長按菜單 listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle("長按菜單-ContextMenu"); menu.add(0, 0, 0, "查看詳細"); menu.add(0, 1, 0, "發送信息"); menu.add(0, 2, 0, "刪除聯系人"); } }); } public boolean onContextItemSelected(MenuItem item) { // setTitle("點擊了長按菜單裡面的第"+item.getItemId()+"個項目"); Toast.makeText(getApplicationContext(), "選擇了" + item.getItemId() + item.getTitle() + "項", Toast.LENGTH_LONG).show(); int id = item.getItemId(); // 查看詳細 if (id == 0) { Intent intent = new Intent(); intent.putExtra("ymw", item.getTitle()); intent.setClass(MainActivity.this, Detail.class); startActivity(intent); } // 發送短信 else if (id == 1) { Uri uri = Uri.parse("smsto://18664599745"); Intent intent = new Intent(Intent.ACTION_SENDTO, uri); intent.putExtra("sms_body", "ymw-LOVE-yh"); startActivity(intent); } // 刪除聯系人 else if (id == 2) { } return super.onContextItemSelected(item); } // 獲取手機聯系人列表方法一 public ArrayList<HashMap<String, Object>> GetContects() { ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); Cursor cursor = getContentResolver().query( ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); if (cursor.moveToFirst()) { int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID); int nameColum = cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); do { String contactId = cursor.getString(idColumn); String disPlayNameString = cursor.getString(nameColum); // 查看有多少電話號碼 沒有則返回為0 int phoneCount = cursor .getInt(cursor .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); if (phoneCount > 0) { // 獲得聯系人的電話號碼 Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("imgView", R.drawable.ic_launcher); map.put("name", disPlayNameString); list.add(map); } } while (cursor.moveToNext()); if (cursor != null) cursor.close(); } return list; } // 獲取聯系人方法二 public ArrayList<HashMap<String, Object>> fillMaps() { ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>(); ContentResolver cr = getContentResolver(); HashMap<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList<String>>(); Cursor phone = cr.query(CommonDataKinds.Phone.CONTENT_URI, new String[] { CommonDataKinds.Phone.CONTACT_ID, CommonDataKinds.Phone.DISPLAY_NAME, CommonDataKinds.Phone.NUMBER, CommonDataKinds.Phone.DATA1 // CommonDataKinds.StructuredPostal.DATA3, }, null, null, null); while (phone.moveToNext()) { String contactId = phone.getString(phone .getColumnIndex(CommonDataKinds.Phone.CONTACT_ID)); String displayName = phone.getString(phone .getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME)); String PhoneNumber = phone .getString(phone .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); String address = phone.getString(phone .getColumnIndex(CommonDataKinds.Phone.DATA1)); // 以contactId為主鍵,把同一人的所有電話都存到一起。 ArrayList<String> ad = hashMap.get(contactId); if (ad == null) { ad = new ArrayList<String>(); ad.add(displayName); ad.add(PhoneNumber); // ad.add(address); hashMap.put(contactId, ad); } else { ad.add(PhoneNumber); } } phone.close(); ArrayList<String> tmpList; String tmpStr = ""; int k; Iterator iter = hashMap.entrySet().iterator(); while (iter.hasNext()) { HashMap.Entry entry = (HashMap.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); tmpList = (ArrayList) val; tmpStr = ""; for (k = 1; k < tmpList.size(); k++) { tmpStr = tmpStr + tmpList.get(k) + ','; } tmpStr = GetString(tmpStr); HashMap<String, Object> tmpMap = new HashMap<String, Object>(); tmpMap.put("name", tmpList.get(0)); tmpMap.put("number", tmpStr); tmpMap.put("imgView", R.drawable.ic_launcher); items.add(tmpMap); } return items; } private String GetString(String str) { String strLast = ""; int i = str.lastIndexOf(","); if (i > 0) { strLast = str.substring(0, str.length() - 1); } return strLast.replace(" ", "").replace(",", "\n").replace("+86", ""); } }
b. Detail.java:長按選單中「查看詳細」的跳轉目標,負責接收主介面傳來的參數並顯示。
package com.ymw.details; import com.example.myandroid.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class Detail extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(com.example.myandroid.R.layout.phonedetails); Intent intent = getIntent(); String strPara = intent.getStringExtra("ymw"); TextView tView = (TextView) findViewById(R.id.ymw); tView.setText(strPara); } }
3. 要讀取聯絡人、撥號與傳送簡訊,還需要在 AndroidManifest.xml 的 application 節點上加入對應權限:
<!--添加權限--> <uses-permission android:name="android.permission.SEND_SMS"/> <uses-permission android:name="android.permission.CALL_PHONE"/> <uses-permission android:name="android.permission.READ_CONTACTS"/>
4. 最後,用模擬器或實機運行本程式,即可看到手機聯絡人列表:單擊某個聯絡人會直接撥號,長按則會彈出選單,可選擇傳送簡訊。特別提醒,以上權限在 Android 6.0 以後屬於危險權限,需要在執行期以 requestPermissions() 動態向使用者申請,才能真正讀取到聯絡人資料。希望本文對你的 Android 開發有所幫助。
Android 系統移植實戰:客製化開機後的系統預設設定
本文記錄一次針對特定客戶機型客製化 Android 系統預設值的完整過程,包含開發者選項、USB 除錯與未知來源的預設開啟。 一、讓「開發者選項」預設顯示 相關源碼位於
如何在 Android 中實現漸顯按鈕的左右滑動效果
本範例要做的效果是:左右兩側各有一個浮動箭頭按鈕,平常隱藏,手指觸碰螢幕時漸顯,放開後淡出。頁面本身則用 ViewFlipper 承載多張圖片,可左右切換。 專案結
Android AutoCompleteTextView 搭配 TextWatcher 動態提示
AutoCompleteTextView 是什麼 AutoCompleteTextView 是可動態提示輸入內容的輸入框。當使用者輸入部分文字時,它會顯示候選清單,例如輸
在 Eclipse 中使用 Android Studio Gradle AAR 庫的完整指南
為何需要在 Eclipse 中使用 AAR許多新的 Android 庫以 Android Studio 的 Gradle 專案形式發布,並以 AAR 形式進入公共倉庫。然