android读取短信示例分享
package com.homer.sms;
import java.sql.date;
import java.text.simpledateformat;
import android.app.activity;
import android.database.cursor;
import android.database.sqlite.sqliteexception;
import android.net.uri;
import android.os.bundle;
import android.util.log;
import android.widget.scrollview;
import android.widget.tablelayout;
import android.widget.textview;
public class smsread extends activity {
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
textview tv = new textview(this);
tv.settext(getsmsinphone());
scrollview sv = new scrollview(this);
sv.addview(tv);
setcontentview(sv);
}
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";
final string sms_uri_outbox = "content://sms/outbox";
final string sms_uri_failed = "content://sms/failed";
final string sms_uri_queued = "content://sms/queued";
stringbuilder smsbuilder = new stringbuilder();
try {
uri uri = uri.parse(sms_uri_all);
string[] projection = new string[] { "_id", "address", "person", "body", "date", "type" };
cursor cur = getcontentresolver().query(uri, projection, null, null, "date desc"); // 获取手机内部短信
if (cur.movetofirst()) {
int index_address = cur.getcolumnindex("address");
int index_person = cur.getcolumnindex("person");
int index_body = cur.getcolumnindex("body");
int index_date = cur.getcolumnindex("date");
int index_type = cur.getcolumnindex("type");
do {
string straddress = cur.getstring(index_address);
int intperson = cur.getint(index_person);
string strbody = cur.getstring(index_body);
long longdate = cur.getlong(index_date);
int inttype = cur.getint(index_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 = "接收";
} else if (inttype == 2) {
strtype = "发送";
} else {
strtype = "null";
}
smsbuilder.append("[ ");
smsbuilder.append(straddress + ", ");
smsbuilder.append(intperson + ", ");
smsbuilder.append(strbody + ", ");
smsbuilder.append(strdate + ", ");
smsbuilder.append(strtype);
smsbuilder.append(" ]\n\n");
} while (cur.movetonext());
if (!cur.isclosed()) {
cur.close();
cur = null;
}
} else {
smsbuilder.append("no result!");
} // end if
smsbuilder.append("getsmsinphone has executed!");
} catch (sqliteexception ex) {
log.d("sqliteexception in getsmsinphone", ex.getmessage());
}
return smsbuilder.tostring();
}
}
记得在androidmanifest.xml中加入android.permission.read_sms这个permission
<uses-permission android:name="android.permission.read_sms" />