我正在使用广播接收器来读取新传入的短信。我的问题是当来自联系人的新短信收到时,我的代码无法返回我的联系人的最后一条消息,它会在最后一条消息之前返回该消息。 请帮我纠正我的代码。我真的很困惑。
public static class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
readVerificationCodeFromInbox();
}
}
}
}
public static void readVerificationCodeFromInbox() {
long currentTime = System.currentTimeMillis();
Uri message = Uri.parse("content://sms/");
ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
try {
if (c.moveToFirst()) {
do {
if (c.getString(c.getColumnIndexOrThrow("address")) == null) {
c.moveToNext();
continue;
}
if (c.getString(c.getColumnIndexOrThrow("address")).equalsIgnoreCase("9101620")){
long date = c.getLong(c.getColumnIndexOrThrow("date"));
Log.d("date-->", "" + date);
String Body =c.getString(c.getColumnIndexOrThrow("body")).toString();
String numberOnly= Body.replaceAll("[^0-9]", "");
Log.d("Body-->", "" + numberOnly);
if (currentTime-date<0.25*3600*1000) {
confirm_number.setText(numberOnly);
// EnterVerificationCode(numberOnly);
}else{
Toast.makeText(context, R.string.retry_get_verificationCode_time, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
break;
}
} while (c.moveToNext());
}
c.close();
context.unregisterReceiver(receiver);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
AndroidManifest.xml中接收器的优先级是什么?我遇到了同样的问题,因为我选择了一个积极的优先级,我的接收器比默认的Android SMS接收器更优先。实际上发生的事情是,我试图在Android短信接收器之前阅读该消息并将其放入我们通过内容解析器访问的默认SMS数据库。
尝试选择优先级为负值,它应该有效。
PS:这应该是评论,但由于我没有足够的声誉,因此无法发布。