我的应用会收听新的短信&n; n。现在,当我收到一个新的时,我创建了一个SmsMessage。为了对此进行进一步的操作,我需要消息的Id。所以我查询内容解析器,如下所示:
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
//get the protocol discription unit ( SMSs)
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
long time_rcv = currentMessage.getTimestampMillis();
String [] relevantColumns = {"_id", "address", "body", "date_sent"};
Cursor cursor = context.getContentResolver().query(
Uri.parse("content://sms/inbox"),
relevantColumns,
"address = '" + phoneNumber + "' AND body = '" + message
+ "' AND date_sent = '" + time_rcv + "'",
null,
null);
if (cursor != null && cursor.moveToFirst()) {
int id = Integer.valueOf(cursor.getString(0));
Log.d(TAG,"ID SMS: " + id);
}
else
Log.e(TAG,"Failed to find ID");
Log.i(TAG, "FROM: " + phoneNumber + "; MSG: " + message);
Toast.makeText(context, "From: " + phoneNumber + ", MSG: " + message, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
Log.e(TAG, "Exception receiver" + e);
}
无论发生什么,它都永远不会找到消息。
答案 0 :(得分:0)
我的代码是正确的。唯一的问题是,在我的接收广播完成之前,短信不在短信/收件箱中。因此,下次运行代码并手动填充字段时,代码会找到短信并为您提供ID。