我在对话中两次收到同样的消息。
也许,我的接收器出了问题。
请帮我找一下?
public class SmsReceiver extends BroadcastReceiver {
private final String TAG = "MessagingReceiver";
private Context mContext;
private SharedPreferences mPrefs;
private String mAddress;
private String mBody;
private long mDate;
private Uri mUri;
public static final String SMS_URI = "content://sms";
public static final Uri RECEIVED_MESSAGE_CONTENT_PROVIDER = Uri.parse("content://sms/inbox");
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
abortBroadcast();
mContext = context;
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
if (intent.getExtras() != null) {
Object[] pdus = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
SmsMessage sms = messages[0];
if (messages.length == 1 || sms.isReplace()) {
mBody = sms.getDisplayMessageBody();
} else {
StringBuilder bodyText = new StringBuilder();
for (SmsMessage message : messages) {
bodyText.append(message.getMessageBody());
}
mBody = bodyText.toString();
}
mAddress = sms.getDisplayOriginatingAddress();
mDate = sms.getTimestampMillis();
addMessageToInbox(mContext, mAddress, mBody, mDate);
}
}
public static Uri addMessageToInbox(Context context, String address, String body, long time) {
ContentResolver contentResolver = context.getContentResolver();
ContentValues cv = new ContentValues();
cv.put("address", address);
cv.put("body", body);
cv.put("date_sent", time);
return contentResolver.insert(RECEIVED_MESSAGE_CONTENT_PROVIDER, cv);
}
}
的Manifest.xml
<receiver android:name=".SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
答案 0 :(得分:0)
实际上,我曾两次调用onReceive()。一旦进入上述广播接收器。其次,我将这个广播接收器扩展到另一个接收器。这就是双重消息背后的原因