java 代码:
package com.cs.smstest;
setContentView(R.layout.main);
//获取手机短信:
tv.setMovementMethod(new ScrollingMovementMethod());//设置textview可滚动
//删除手机短信
deleteSMS();
* 参数说明
*
* @since 1.0
* @author zlp
* @time 2014-1-15 下午3:14:16
*/
public void deleteSMS(){
try{
ContentResolver cr=getContentResolver();
Uri urisms=Uri.parse("content://sms/");
Cursor c=cr.query(urisms,new String[]{"_id", "thread_id" }, null, null, null);
if(null!=c && c.moveToFirst()){
do{
long threadid=c.getLong(1);
String ss=c.getString(0)+c.getString(1);
cr.delete(Uri.parse("content://sms/conversations/" +threadid),
null, null);
Log.d("deleteSMS", "threadId:: "+threadid);
}while(c.moveToNext());
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 获取手机短信内容
* @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();
}
}
获取短信内容需要界面显示:
布局文件:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:scrollbars="vertical"
/>
不要忘记添加权限:
手机短信的读写权限