獲取聯繫人,短信,通話記錄

安卓的聯繫人,短信和通話記錄能夠經過一個叫作ContentResolver的類來讀取 而獲取ContentResolver是經過Context獲取的正則表達式

ContentResolver cr = getApplicationContext().getContentResolver();
複製代碼

獲取聯繫人json

//contactsNum表明數量
public static String getAllContact(ContentResolver cr, int contactsNum) {
        Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, null, null, null);
        JSONArray jsonarray = new JSONArray();//json數組
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                if (cursor.getPosition() > contactsNum - 1) {
                    continue;
                }
                // 取得聯繫人的名字索引
                int nameIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
                String contact = cursor.getString(nameIndex);
                String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                JSONObject jsonObj = new JSONObject();//對象,json形式
                phone = phone.replace(" ", "");
                if (!TextUtils.isEmpty(contact) && !TextUtils.isEmpty(phone)) {
                    try {
                        jsonObj.put("name", contact);//向pet對象裏面添加值
                        jsonObj.put("phone", phone);
                        // 把每一個數據看成一對象添加到數組裏
                        jsonarray.put(jsonObj);//向json數組裏面添加pet對象
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            cursor.close();
        } 
        if (jsonarray.length() <= 0) {
            ToastUtils.showToast("請檢查聯繫人");
        }
        return jsonarray.toString();
    }
複製代碼

獲取短信數組

public static String getSmsInPhone(ContentResolver cr, int smsNum) {
        final String SMS_URI_ALL = "content://sms/";
        JSONArray jsonarray = new JSONArray();//json數組
        try {
            Uri uri = Uri.parse(SMS_URI_ALL);
            String[] projection = new String[]{"_id", "address", "person",
                    "body", "date", "type"};
            Cursor cur = cr.query(uri, projection, null,
                    null, "date desc"); // 獲取手機內部短信
            if (cur != null && cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    if (cur.getPosition() > smsNum - 1) {
                        continue;
                    }
                    JSONObject jsonObj = new JSONObject();//對象,json形式
                    String strAddress = cur.getString(cur.getColumnIndex("address"));
                    String strPerson = cur.getString(cur.getColumnIndex("person"));
                    String strbody = cur.getString(cur.getColumnIndex("body"));
                    long longDate = cur.getLong(cur.getColumnIndex("date"));
                    int intType = cur.getInt(cur.getColumnIndex("type"));

                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd hh:mm:ss");
                    Date d = new Date(longDate);
                    String strDate = dateFormat.format(d);
                    String strType = "";
                    if (intType == 1) {
                        strType = "in";
                    } else if (intType == 2) {
                        strType = "out";
                    } else {
                        strType = "null";
                    }
                    jsonObj.put("name", strPerson);//向pet對象裏面添加值
                    jsonObj.put("phone", strAddress);
                    jsonObj.put("direction", strType);
                    jsonObj.put("sendTime", strDate);
                    jsonObj.put("content", strbody);
                    jsonarray.put(jsonObj);
                }
                cur.close();
            }
        } catch (SQLiteException ex) {
            ex.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonarray.toString();
    }
複製代碼

獲取通話記錄bash

public static String getCallsInPhone(ContentResolver cr, int callRecordNum) {


        Cursor cursor = cr.query(
                CallLog.Calls.CONTENT_URI,
                new String[]{CallLog.Calls.DURATION, CallLog.Calls.TYPE, CallLog.Calls.DATE,
                        CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME}, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);

        JSONArray jsonarray = new JSONArray();//json數組
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                if (cursor.getPosition() > callRecordNum - 1) {
                    continue;
                }
                JSONObject jsonObj = new JSONObject();//對象,json形式
                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
                long duration = cursor.getLong(cursor
                        .getColumnIndex(CallLog.Calls.DURATION));
                String strPhone = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyy-MM-dd hh:mm:ss");
                Date d = new Date(Long.parseLong(cursor.getString(cursor
                        .getColumnIndex(CallLog.Calls.DATE))));
                String date = dateFormat.format(d);
                String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));

                String strType = "";
                switch (type) {
                    case CallLog.Calls.INCOMING_TYPE:
                        strType = "in";
                        break;
                    case CallLog.Calls.OUTGOING_TYPE:
                        strType = "out";
                        break;
                    case CallLog.Calls.MISSED_TYPE:
                        strType = "in";
                        break;

                    default:
                        break;
                }

                try {
                    if (TextUtils.isEmpty(name)) {
                        jsonObj.put("name", "");
                    } else {
                        jsonObj.put("name", name);
                    }
                    jsonObj.put("phone", strPhone);
                    jsonObj.put("direction", strType);
                    jsonObj.put("duration", duration);
                    jsonObj.put("callTime", date);
                    // 把每一個數據看成一對象添加到數組裏
                    jsonarray.put(jsonObj);//向json數組裏面添加pet對象
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return jsonarray.toString();
    }
複製代碼

獲取驗證碼 咱們能夠經過ContentObserver來獲取相應的短信信息,可是要注意一點就是要對ContentObserver進行註銷。ide

public class MessageContentObserver extends ContentObserver {
    public final String SMS_URI_INBOX = "content://sms/inbox";//收信箱
    private String smsContent = "";//驗證碼
    private EditText verifyText = null;//驗證碼編輯框
    private String smsAddress = null;//短信發送提供商
    private String smsID = "";

    //短信觀察者 收到一條短信時 onchange方法會執行兩次,因此比較短信id,若是一致則不處理
    public MessageContentObserver(Handler handler, EditText verifyText) {
        super(handler);
        this.verifyText = verifyText;
    }

    public MessageContentObserver(Handler handler, EditText verifyText, String smsAddressNumber) {
        super(handler);
        this.verifyText = verifyText;
        this.smsAddress = smsAddressNumber;
    }

    @NeedPermission(PermissionStringUtils.PERMISSION_SMS)
    @Override
    public void onChange(boolean selfChange) {
        Cursor cursor = null;// 光標
        // 讀取收件箱中指定號碼的短信
        if (!TextUtils.isEmpty(smsAddress)) {
            cursor = AppUtils.getContext().getContentResolver().query(Uri.parse(SMS_URI_INBOX),
                    new String[]{"_id", "address", "body", "read"}, //要讀取的屬性
                    null, //查詢條件是什麼
                    new String[]{smsAddress, "0"},//查詢條件賦值
                    "date desc");//排序
        } else {
            cursor = AppUtils.getContext().getContentResolver().query(Uri.parse(SMS_URI_INBOX),
                    new String[]{"_id", "address", "body", "read"}, //要讀取的屬性
                    null, //查詢條件是什麼
                    null,//查詢條件賦值
                    "date desc");//排序
        }

        if (cursor != null && cursor.getCount() > 0) {

            if (cursor.moveToFirst()) {
                //比較和上次接收到短信的ID是否相等
                if (!smsID.equals(cursor.getString(cursor.getColumnIndex("_id"))) && cursor.getString(cursor.getColumnIndex("body")).contains("驗證碼")) {
                    String smsbody = cursor.getString(cursor.getColumnIndex("body"));
                    //用正則表達式匹配驗證碼   不肯定幾位
                    Pattern pattern = Pattern.compile("[0-9]{4,9}");
                    Matcher matcher = pattern.matcher(smsbody);
                    if (matcher.find()) {//匹配到6位的驗證碼
                        smsContent = matcher.group();
                        if (verifyText != null && !TextUtils.isEmpty(smsContent)) {
                            verifyText.requestFocus();//獲取焦點
                            verifyText.setText(smsContent);//設置文本
                            verifyText.setSelection(smsContent.length());//設置光標位置
                        }
                    }
                    smsID = cursor.getString(cursor.getColumnIndex("_id"));
                }
            }
            cursor.close();
        }
    }

    public void onDestory() {
        if (verifyText != null) {
            verifyText = null;
        }
        if (!TextUtils.isEmpty(smsAddress))
            smsAddress = null;
    }

}
複製代碼

註銷ContentObserverui

public void unRegister() {
        if (messageContentObserver != null) {
            messageContentObserver.onDestory();
            AppUtils.getContext().getContentResolver().unregisterContentObserver(messageContentObserver);
            messageContentObserver = null;
        }
    }

複製代碼
相關文章
相關標籤/搜索