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

Android 常用系統能力工具類:通話、聯繫人、短信與文件讀寫一站式封裝

編輯:關於 Android 程式設計

日常開發中,撥打電話、讀寫聯繫人、操作短信、讀寫 SD 卡文件這些功能反覆出現。與其每次翻文檔重寫,不如把它們沉澱成一個工具類。下面這個 Util 類把常見操作做了統一封裝,可以直接複用到項目中。

一、SD 卡相關

/** 檢測 SDCard 是否正常 */
public static boolean checkSDcard() {
    return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}

/** 從 SDCard 讀取文件內容 */
public static String readFileFromSDcard(String path, String filename) throws IOException {
    if (!checkSDcard()) return null;
    path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + path;
    File dir = new File(path);
    if (!dir.exists()) dir.mkdirs();

    FileInputStream inStream = new FileInputStream(new File(dir, filename));
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    while ((len = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }
    byte[] data = outStream.toByteArray();
    outStream.close();
    inStream.close();
    return new String(data);
}

/** 寫入文件到 SDCard */
public static boolean writeFileToSDcard(String path, String filename,
                                        String content, boolean append) throws IOException {
    byte[] buffer = content.getBytes();
    if (!checkSDcard()) return false;
    path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + path;
    File dir = new File(path);
    if (!dir.exists()) dir.mkdirs();

    FileOutputStream out = new FileOutputStream(new File(dir, filename), append);
    out.write(buffer);
    out.flush();
    out.close();
    return true;
}

二、撥打電話

public static void callPhone(String number, Context context) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_CALL);
    intent.setData(Uri.parse("tel:" + number));
    context.startActivity(intent);
}

注意:ACTION_CALL 需要 CALL_PHONE 權限;若不想申請敏感權限,可改用 ACTION_DIAL,由系統打開撥號界面並自動填入號碼,需要用戶手動確認。

三、聯繫人操作

讀取所有聯繫人的姓名與電話,核心是先查 Contacts 表拿到 contactId,再根據 ID 查 Phone 表:

public static List<ContactsInfo> getAllContacts(Context context) {
    List<ContactsInfo> resultList = new ArrayList<>();
    ContentResolver cr = context.getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    while (cur.moveToNext()) {
        String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        String contactId = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
        Cursor phone = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
            null, null);
        while (phone.moveToNext()) {
            String number = phone.getString(phone.getColumnIndex(
                ContactsContract.CommonDataKinds.Phone.NUMBER));
            resultList.add(new ContactsInfo(name, number));
        }
    }
    return resultList;
}

插入聯繫人時,需先向 RawContacts.CONTENT_URI 插入一條空記錄取得 rawContactId,再分別向 Data 表寫入姓名(StructuredName)與電話(Phone)兩條數據。批量插入則推薦使用 ContentProviderOperation 組裝操作列表,最後一次性 applyBatch,性能遠優於循環單條插入。

四、通話記錄

public static boolean insertCallLog(List<CallLogModel> listDate, Context context) {
    for (CallLogModel info : listDate) {
        ContentValues values = new ContentValues();
        values.put(CallLog.Calls.NUMBER, info.getNumber());
        values.put(CallLog.Calls.DATE, info.getDate());
        values.put(CallLog.Calls.DURATION, info.getDuration());
        values.put(CallLog.Calls.TYPE, info.getType());
        values.put(CallLog.Calls.NEW, info.getRend());  // 0 已看,1 未看
        context.getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
    }
    return true;
}

五、短信讀取與批量插入

讀取短信可透過 content://sms/ 這個 URI 查詢,projection 中指定 _id、address、person、body、date、type 等字段,按 date 倒序排列即可得到最新消息優先的列表。插入短信則向 content://sms/inbox 寫入 address、body、date、read、type 即可。

六、配套 JavaBean

工具類依賴三個簡單的數據模型:

  • CallLogModel:number、date、duration(秒)、type(1 來電、2 已撥、3 未接)、rend(0 已看、1 未看)。
  • ContactsInfo:name、number。
  • SmsInfo:linkman、number、content、date、read(0 未讀、1 已讀)、type(1 接收、2 發送、3 草稿)。

此外類中還提供了一個 getMD5 方法,用於對字符串做 MD5 摘要並返回大寫十六進制字符串,常用於接口簽名或數據校驗。

使用提醒

這些能力全部涉及用戶隱私,需要在 AndroidManifest.xml 中聲明 READ_CONTACTS、WRITE_CONTACTS、WRITE_CALL_LOG、READ_SMS、WRITE_SMS 等權限,並針對高版本系統處理運行時權限申請。此外,直接操作系統數據庫具備一定風險,不同 ROM 的實現可能存在差異,上線前務必在多款設備上驗證。

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