Android下如何获得通话记录和短信记录

1.获得通话记录:

private void getCallHistory() {
        Call call = null;
        Cursor cursor = this.getActivity().getContentResolver()
                .query(CallLog.Calls.CONTENT_URI, null, null, null, null);

        if (cursor.getCount() <= 0) {
            return;
        }

        cursor.moveToFirst();
        do {
            call = new Call();

            /* Reading Name */
            String nameTemp = cursor.getString(cursor
                    .getColumnIndex(CallLog.Calls.CACHED_NAME));
            if (nameTemp == null) {
                nameTemp = "";
            }

            if ("".equals(nameTemp)) {
                call.name = "";
            } else {
                call.name = nameTemp;
            }
            /* Reading Date */
            call.date = cursor.getLong(cursor
                    .getColumnIndex(CallLog.Calls.DATE));

            /* Reading duration */
            call.duration = cursor.getLong(cursor
                    .getColumnIndex(CallLog.Calls.DURATION));

            /* Reading Date */
            call.type = cursor
                    .getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));

            call.phoneNumber = cursor.getString(cursor
                    .getColumnIndex(CallLog.Calls.NUMBER));

            calls.add(call);
        } while (cursor.moveToNext());
    }

2. 获得短信记录

private void getAllSms() {
        ContentResolver cr = this.getActivity().getContentResolver();
        Uri uri = Uri.parse("content://sms/");
        Message message = null;
        messages.clear();

        Cursor c = cr.query(uri, null, null, null, null);
        int totalSms = c.getCount();
        if (totalSms <= 0) {
            return;
        }

        if (c.moveToFirst()) {
            for (int i = 0; i < totalSms; i++) {

                message = new Message();
                if (c.getString(
                        c.getColumnIndexOrThrow(Telephony.Sms.Inbox.TYPE))
                        .contains("1")) {
                    message.type = "inbox";
                } else {
                    message.type = "send";
                }
                // message.phoneNumber = c.getString(c
                // .getColumnIndexOrThrow(Telephony.Sms.Inbox.ADDRESS));

                message.phoneNumber = c.getString(c
                        .getColumnIndexOrThrow("address"));

                message.name = getNameByPhoneNumber(cr, message.phoneNumber);

                messages.add(message);

                c.moveToNext();
            }
        }

        c.close();

    }