每次 Android 发送 SMS 时,我都会尝试检索数据。
数据形式:
- 目的地电话号码
- 交货时间
- 短信正文
有人知道怎么做吗?
最佳答案
在发件箱中获取短信。
public List<SmsRep> getOutboxSms()
{
if(null == context)
{
return new ArrayList<SmsRep>();
}
Uri uriSms = Uri.parse("content://sms/sent");
Cursor cursor = context.getContentResolver().query(uriSms, null,null,null,null);
List<SmsRep> outboxSms = cursor2SmsArray(cursor);
if(!cursor.isClosed())
{
cursor.close();
}
return outboxSms;
}
以及处理发件箱中数据的方法:
public static List<SmsRep> cursor2SmsArray(Cursor cursor)
{
if(null == cursor || 0 == cursor.getCount())
{
return new ArrayList<SmsRep>();
}
List<SmsRep> messages = new ArrayList<SmsRep>();
try
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
SmsRep singleSms = new SmsRep();
singleSms.id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
singleSms.address = cursor.getString(cursor.getColumnIndexOrThrow("address"));
singleSms.timestamp = cursor.getLong(cursor.getColumnIndexOrThrow("date")) / 1000; //### the sent time
singleSms.type = cursor.getInt(cursor.getColumnIndexOrThrow("type"));
singleSms.protocol = cursor.getInt(cursor.getColumnIndexOrThrow("protocol"));
/*
String smsSubject = cursor.getString(cursor.getColumnIndex("subject"));
byte[] subjByts = smsSubject.getBytes("UTF8");
singleSms.subject = new String(subjByts, "UTF8");
*/
String smsBody = cursor.getString(cursor.getColumnIndexOrThrow("body")); //### body
byte[] bodyBytes = smsBody.getBytes("UTF8");
singleSms.body = TextUtils.htmlEncode(new String(bodyBytes, "UTF8")); //escape,handle '='
singleSms.deviceId = deviceId;
//singleSms.body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
messages.add(singleSms);
}
}
catch (Exception e)
{
Log.e(TAG, e.getMessage());
}
finally
{
cursor.close();
}
return messages;
}
SmsRep 的定义:
public class SmsRep
{
static String separator ;
public int id;
public String address;
public long timestamp;
public int type;
public int protocol;
public String subject;
public String body;
public String deviceId;
public SmsRep()
{
// do nothing in ctor
}
}
这是你想要的吗?:)
关于android - 从发送的短信中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5451354/