我在消息传递应用程序中构建了以下Receiver类,它随时接收SMS消息:
public class Receiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
smgs = new SmsMessage[pdus.length];
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
infoSender += smgs[i].getOriginatingAddress();
infoSMS += smgs[i].getMessageBody().toString();
}
}
}
}
它的问题在于它有时会多次收到相同的消息,所以我怀疑它是因为接收器没有注册和销毁,所以它经常检查传入的消息。
因此,我尝试过实现这个典型的接收器类:
public class myReceiver extends MainActivity {
BroadcastReceiver ReceiverOne = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
ReceiverOne = new BroadcastReceiver() {
@Override
public void onReceive(Context arr0, Intent arr1) {
processReceive(arr0, arr1);
}
};
registerReceiver(ReceiverOne, filter);
}
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(ReceiverOne);
}
}
但是现在,ReceiverOne从未被使用过,因为这个类没有布局,因此它从未被调用过。有没有办法将这两个接收器结合起来?
或者更好的是,对于为什么第一个接收者多次收到一些短信,有人会有更好的建议吗?
答案 0 :(得分:0)
以下是您的解决方案获取消息并添加StringBuilder
以使其成为单一的原因,为什么您一次又一次地获取getOriginatingAddress
所有短信部分的相同内容。
public class Receiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
smgs = new SmsMessage[pdus.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
sb.append(smgs[i].getMessageBody());
}
infoSender = smgs[0].getOriginatingAddress();
infoSMS = sb.toString();
}
}
}
}