Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發學習:電話、短信與聯繫人 API 全解析

編輯:關於 Android 程式設計

身為一台手機,最重要的功能莫過於電話、短信與聯繫人。今天整理的主題,就是 Android 在這三塊上提供的 API 接口。

1. 取得通話記錄

List<TelePhoneRecord> mRecords = new ArrayList<TelePhoneRecord>();
Cursor mCursor = mContext.getContentResolver().query(
        CallLog.Calls.CONTENT_URI, null, null, null, null);
if (mCursor != null && mCursor.moveToFirst()) {
    do {
        TelePhoneRecord.getColumnIndex(mCursor);
        TelePhoneRecord mRecord = new TelePhoneRecord(mCursor);
        mRecords.add(mRecord);
    } while (mCursor.moveToNext());
}
mCursor.close();

其中 TelePhoneRecord 是描述通話記錄的實體類別:

package com.android.TelephoneAPIs.Tools;

import android.database.Cursor;

public class TelePhoneRecord {
    /** 通話記錄 ID **/        private long mID;
    /** 電話號碼 **/            private String mNumber;
    /** 通話日期 **/            private long mDate;
    /** 通話類型(1 來電、2 去電)**/ private long mType;
    /** 通話時長 **/            private long mDuration;

    private static int Index_ID;
    private static int Index_Number;
    private static int Index_Date;
    private static int Index_Type;
    private static int Index_Duration;

    public static void getColumnIndex(Cursor c) {
        Index_ID = c.getColumnIndex("_id");
        Index_Number = c.getColumnIndex("number");
        Index_Date = c.getColumnIndex("date");
        Index_Type = c.getColumnIndex("type");
        Index_Duration = c.getColumnIndex("duration");
    }

    public TelePhoneRecord(Cursor c) {
        mID = c.getLong(Index_ID);
        mNumber = c.getString(Index_Number);
        mDate = c.getLong(Index_Date);
        mType = c.getLong(Index_Type);
        mDuration = c.getLong(Index_Duration);
    }

    // 各欄位的 getter / setter 略
}

2. 監聽來電、去電與短信

監聽來電:繼承 BroadcastReceiver,在 onReceive 中判斷 Intent 的 action,或用 TelephonyManager 取得電話狀態。

監聽去電:同樣繼承 BroadcastReceiver,在 onReceive 中判斷 Intent 類型。

監聽短信:在 BroadcastReceiver 中從 Bundle 取出 pdus 資料,轉換成 SmsMessage 物件。

3. 讀取聯繫人

List<Contact> mContacts = new ArrayList<Contact>();

// 此路徑只能查詢聯繫人名稱
// Cursor c1 = mContext.getContentResolver().query(
//         Uri.withAppendedPath(ContactsContract.AUTHORITY_URI, "contacts"), null, null, null, null);

// 此路徑可以同時查詢聯繫人名稱與號碼
Cursor c2 = mContext.getContentResolver().query(
        Uri.withAppendedPath(ContactsContract.AUTHORITY_URI, "data/phones"), null, null, null, null);
if (c2 != null && c2.moveToFirst()) {
    do {
        Contact.getColumnIndex(c2);
        Contact mContact = new Contact(c2);
        mContacts.add(mContact);
    } while (c2.moveToNext());
}
c2.close();

Contact 的定義:

package com.android.TelephoneAPIs.Tools;

import android.database.Cursor;

public class Contact {
    private String mName;
    private String mNum;

    private static int Index_Name;
    private static int Index_Num;

    public static void getColumnIndex(Cursor c) {
        Index_Name = c.getColumnIndex("display_name");
        Index_Num = c.getColumnIndex("data1");
    }

    public Contact(Cursor c) {
        mName = c.getString(Index_Name);
        mNum = c.getString(Index_Num);
    }

    // getter / setter 略
}

4. 新增聯繫人

新增聯繫人的關鍵是兩步走:先建立 RawContact 取得 ID,再把名稱與號碼分別作為兩筆 Data 記錄掛上去。

ContentValues mValues = new ContentValues();

// 取得 RawContactID
Uri mRawContactUri = mContext.getContentResolver().insert(RawContacts.CONTENT_URI, mValues);
long mRawContactID = ContentUris.parseId(mRawContactUri);
mValues.clear();

// 寫入姓名
mValues.put(StructuredName.RAW_CONTACT_ID, mRawContactID);
mValues.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
mValues.put(StructuredName.DISPLAY_NAME, Name);
mContext.getContentResolver().insert(Data.CONTENT_URI, mValues);
mValues.clear();

// 寫入號碼
mValues.put(Phone.RAW_CONTACT_ID, mRawContactID);
mValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
mValues.put(Phone.NUMBER, Num);
mContext.getContentResolver().insert(Data.CONTENT_URI, mValues);

注意 MIMETYPE 要與資料類型對應(姓名用 StructuredName,號碼用 Phone),否則寫入會失敗。

5. 短信讀取

package com.android.TelephoneAPIs.Tools;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public class ShortMessageReader {

    /** 收件箱 **/      public static final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
    /** 所有短信 **/    public static final Uri SMS_ALL   = Uri.parse("content://sms");
    /** 寄件箱 **/      public static final Uri SMS_TOBOX = Uri.parse("content://sms/sent");

    /** 取得所有短消息 **/
    public static List<ShortMessage> getAllMessages(Context mContext) {
        return queryMessage(mContext, SMS_ALL, null, null);
    }

    /** 取得指定號碼的短消息 **/
    public static List<ShortMessage> getMessageByNumber(Context mContext, Uri mUri, String[] mSelectionAns) {
        return queryMessage(mContext, mUri, "address=?", mSelectionAns);
    }

    /** 取得指定會話 ID 的短消息 **/
    public static List<ShortMessage> getMessageByThreadID(Context mContext, Uri mUri, String[] mSelectionAns) {
        return queryMessage(mContext, mUri, "thread_id=?", mSelectionAns);
    }

    /** 取得任何符合條件的短消息 **/
    public static List<ShortMessage> queryMessage(Context mContext, Uri mUri,
                                                  String mSelection, String[] mSelectionAns) {
        List<ShortMessage> Messages = new ArrayList<ShortMessage>();
        Cursor mCursor = mContext.getContentResolver().query(mUri, null, mSelection, mSelectionAns, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            do {
                ShortMessage.getColumnIndex(mCursor);
                Messages.add(new ShortMessage(mCursor));
            } while (mCursor.moveToNext());
        }
        mCursor.close();
        return Messages;
    }
}

ShortMessage 的欄位定義如下,核心是把 Cursor 的欄位索引先抽出來,再一次性取值:

package com.android.TelephoneAPIs.Tools;

import android.database.Cursor;

public class ShortMessage {
    private long mThreadID;     // 短消息會話 ID
    private long mID;           // 短消息 ID
    private String mBody;       // 內容
    private String mSubject;    // 主題
    private long mDate;         // 發送時間
    private String mAddress;    // 發送號碼
    private int mPerson;        // 發送人
    private int mRead;          // 狀態
    private int mType;          // 類型

    private static int Index_Thread_ID, Index_ID, Index_Address, Index_Date;
    private static int Index_Subject, Index_Body, Index_Person, Index_Read, Index_Type;

    public static void getColumnIndex(Cursor c) {
        Index_Thread_ID = c.getColumnIndex("thread_id");
        Index_ID        = c.getColumnIndex("_id");
        Index_Address   = c.getColumnIndex("address");
        Index_Date      = c.getColumnIndex("date");
        Index_Subject   = c.getColumnIndex("subject");
        Index_Body      = c.getColumnIndex("body");
        Index_Person    = c.getColumnIndex("person");
        Index_Read      = c.getColumnIndex("read");
        Index_Type      = c.getColumnIndex("type");
    }

    public ShortMessage(Cursor c) {
        mThreadID = c.getLong(Index_Thread_ID);
        mID       = c.getLong(Index_ID);
        mAddress  = c.getString(Index_Address);
        mSubject  = c.getString(Index_Subject);
        mDate     = c.getLong(Index_Date);
        mBody     = c.getString(Index_Body);
        mPerson   = c.getInt(Index_Person);
        mRead     = c.getInt(Index_Read);
        mType     = c.getInt(Index_Type);
    }

    // getter / setter 略
}

6. 發送短信

public static void sendMessage(Context mContext, String mNum, String mContent, boolean mSave) {
    SmsManager mManager = SmsManager.getDefault();
    mManager.sendTextMessage(mNum, null, mContent, null, null);

    if (mSave) {
        ContentValues mValues = new ContentValues();
        mValues.put("thread_id", getThreadIDByAddress(mContext, new String[]{mNum}));
        mValues.put("body", mContent);
        mValues.put("date", new Date().getTime());
        mValues.put("address", mNum);
        mValues.put("type", 2);
        mValues.put("read", 1);
        mContext.getContentResolver().insert(Uri.parse("content://sms"), mValues);
    }
}

private static long getThreadIDByAddress(Context mContext, String[] SelectionArg) {
    List<ShortMessage> mMessages =
            ShortMessageReader.getMessageByNumber(mContext, ShortMessageReader.SMS_INBOX, SelectionArg);
    return mMessages.get(0).getThreadID();
}

這個方法可以選擇是否把發送記錄寫回資料庫。實務上要留意:如果收件方從未收過該號碼的短信,getMessageByNumber 會傳回空清單,直接取第 0 筆會出錯,記得先判空。

7. 以 XML 檔形式匯出短信

public static void OutputByXml(List<ShortMessage> mMessages, String mXmlFilePath) {
    File XmlFile = new File(mXmlFilePath);
    try {
        XmlFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(XmlFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }

    XmlSerializer serializer = Xml.newSerializer();
    try {
        serializer.setOutput(fos, "UTF-8");
        serializer.startDocument(null, true);
        serializer.startTag(null, "ShortMessages");
        for (int i = 0; i < mMessages.size(); i++) {
            serializer.startTag(null, "Message");
            serializer.startTag(null, "Address");
            serializer.text(mMessages.get(i).getAddress());
            serializer.endTag(null, "Address");
            serializer.startTag(null, "Body");
            serializer.text(mMessages.get(i).getBody());
            serializer.endTag(null, "Body");
            serializer.endTag(null, "Message");
        }
        serializer.endTag(null, "ShortMessages");
        serializer.endDocument();
        serializer.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

所需權限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

最後提醒:短信與聯繫人權限屬於高敏感群組,較新的 Android 版本必須在執行期動態向使用者申請,而且上架時需要通過審核說明用途。另外,直接呼叫 Uri.parse("content://sms") 這類字串在 Android 4.4 之後已被限制,建議改用 Telephony.Sms 與 Telephony.TextBasedSmsColumns 常數。

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