一、添加权限
<uses-permission android:name="android.permission.READ_SMS" />
/**
* 获取手机短信内容
* @return
*/
public String getSmsInPhone() {
final String SMS_URI_ALL = "content://sms/"; //所有短信
final String SMS_URI_INBOX = "content://sms/inbox"; //收信箱
final String SMS_URI_SEND = "content://sms/sent"; //发信箱
final String SMS_URI_DRAFT = "content://sms/draft"; //草稿箱
StringBuilder smsBuilder = new StringBuilder();
try {
ContentResolver cr = getContentResolver();
String[] projection = new String[] { "_id", "address", "person",
"body", "date", "type" };
Uri uri = Uri.parse(SMS_URI_ALL);
Cursor cur = cr.query(uri, projection, null, null, "date desc");
if (cur.moveToFirst()) {
String name;
String phoneNumber;
String smsbody;
String date;
String type;
int nameColumn = cur.getColumnIndex("person");//姓名
int phoneNumberColumn = cur.getColumnIndex("address");//手机号
int smsbodyColumn = cur.getColumnIndex("body");//短信内容
int dateColumn = cur.getColumnIndex("date");//日期
int typeColumn = cur.getColumnIndex("type");//收发类型 1表示接受 2表示发送
do {
name = cur.getString(nameColumn);
phoneNumber = cur.getString(phoneNumberColumn);
smsbody = cur.getString(smsbodyColumn);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
Date d = new Date(Long.parseLong(cur.getString(dateColumn)));
date = dateFormat.format(d);
int typeId = cur.getInt(typeColumn);
if (typeId == 1) {
type = "接收";
} else if (typeId == 2) {
type = "发送";
} else {
type = "";
}
smsBuilder.append("[");
smsBuilder.append(name + ",");
smsBuilder.append(phoneNumber + ",");
smsBuilder.append(smsbody + ",");
smsBuilder.append(date + ",");
smsBuilder.append(type);
smsBuilder.append("] ");
if (smsbody == null)
smsbody = "";
} while (cur.moveToNext());
} else {
smsBuilder.append("没有记录!");
}
smsBuilder.append("获取彩信完成!");
} catch (SQLiteException ex) {
Log.d("SQLiteException in getSmsInPhone", ex.getMessage());
}
return smsBuilder.toString();
}
三、原代码下载
http://download.youkuaiyun.com/detail/thundercat/4069271