Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 讀取通訊錄、撥打電話、發送短信與長按菜單綜合實戰

編輯:Android 開發實例

這是一個把多個基礎知識點串起來的小項目:用 ListView 展示手機通訊錄,單擊直接撥號,長按彈出菜單,菜單裡可以查看詳情或發送短信。適合拿來熟悉 ContentProvider 查詢與 ContextMenu 的用法。

一、項目結構

主要涉及圖中標示的幾個文件。

二、布局部分

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——條目模板,左圖標、中姓名、右號碼:

 <?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>

三、MainActivity.java

核心是三件事:查詢通訊錄並封裝成 SimpleAdapter 可用的數據、註冊長按菜單、在 onContextItemSelected 中分發菜單項行為。

 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);

        // 取得通訊錄數據並綁定 SimpleAdapter
        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.makeText(getApplicationContext(),
                        "第" + arg2 + "項" + name, Toast.LENGTH_LONG).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, "刪除聯系人");
            }
        });
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        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) {   // 刪除聯系人
            // 需要 ContentResolver.delete 配合權限,此處留空
        }
        return super.onContextItemSelected(item);
    }

    /** 讀取方式一:先查 Contacts 拿 _ID 與 HAS_PHONE_NUMBER,再查 Phone */
    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;
    }

    /** 讀取方式二:直接查 Phone 表,以 contactId 為鍵聚合同一人的多個號碼 */
    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
                }, 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));

            // 以 contactId 為主鍵,把同一人的所有號碼收攏到一起
            ArrayList<String> ad = hashMap.get(contactId);
            if (ad == null) {
                ad = new ArrayList<String>();
                ad.add(displayName);
                ad.add(PhoneNumber);
                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 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;
    }

    /** 清理拼接多號碼時產生的尾逗號與 +86 前綴 */
    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", "");
    }
}

四、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) {
        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);
    }
}

五、權限配置

讀通訊錄、撥號、發短信都屬於敏感能力,必須在 AndroidManifest.xml 中聲明:

 <!--添加權限-->
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>

六、運行效果與幾點重要提醒

運行後可以看到通訊錄列表:單擊某項直接撥號,長按則彈出菜單,可選查看詳情或發送短信。

不過必須強調幾點,否則在現代 Android 版本上這個示例是跑不起來的:

1. 運行時權限。從 Android 6.0(API 23)開始,READ_CONTACTS、CALL_PHONE、SEND_SMS 都屬於危險權限,僅在 Manifest 中聲明是不夠的,必須用 ActivityCompat.requestPermissions 在運行時動態申請並處理 onRequestPermissionsResult 的結果。

2. ACTION_CALL 的替代方案。出於用戶體驗與審核政策考慮,現在更推薦使用 Intent.ACTION_DIAL 只跳到撥號盤並帶入號碼,由用戶自行確認撥出,而不是直接建立通話。

3. 查詢性能。fillMaps() 中把全部通訊記錄一次性加載進內存並做字符串拼接,聯繫人較多時會明顯卡頓。更好的做法是分頁查詢、在 ListView 上做 ViewHolder 複用,或直接在 Adapter 中做異步加載。

4. 隱私合規。讀取通訊錄屬於高敏感數據,實際上線前需要評估是否符合相關隱私政策與上架規範,並向用戶清晰說明用途。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved