Android广播接收器出错,它会收听我手机收到的所有短信

时间:2014-04-23 10:40:20

标签: android broadcastreceiver

我正在做一个加密短信应用,用户可以加密文本并通过我的应用发送短信。 我使用了以下广播接收器。 问题是它听取了我手机上的所有短信。 如何制作它只会收听我的应用发送的短信?其他短信应该正常打开,使用默认的短信应用程序

public class SmsBroadCastReceiver extends BroadcastReceiver{

@Override
 public void onReceive(Context context, Intent intent) {

 Bundle bundle = intent.getExtras();

 // Specify the bundle to get object based on SMS protocol "pdus"
 Object[] object = (Object[]) bundle.get("pdus");
 SmsMessage sms[] = new SmsMessage[object.length]; 
 Intent in=new Intent(context,DisplaySMSActivity.class);
 in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 in.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
 String msgContent = "";
 String originNum = "";
 StringBuffer sb = new StringBuffer();

 for (int i = 0; i < object.length; i++) {

 sms[i] = SmsMessage.createFromPdu((byte[]) object[i]);

 // get the received SMS content
 msgContent = sms[i].getDisplayMessageBody();

 //get the sender phone number
 originNum = sms[i].getDisplayOriginatingAddress();

 //aggregate the messages together when long message are fragmented
 sb.append(msgContent);

 //abort broadcast to cellphone inbox
 abortBroadcast();

 }

 //fill the sender's phone number into Intent
 in.putExtra("originNum", originNum);

 //fill the entire message body into Intent
 in.putExtra("msgContent", new String(sb));

 //start the DisplaySMSActivity.java
 context.startActivity(in);

 }

1 个答案:

答案 0 :(得分:0)

也许您没有正确注册接收器。

在清单中(或以编程方式)声明Receiver时,您还可以指定intent filter。您可以指定要在接收器中接收的“操作”。

例如:“com.your_app_package.sms_encrypted_msg”。

无论哪种方式,请记得检查onReceive方法中的操作:

@Override
public void onReceive(Context context, Intent intent) {
   if(intent.getAction().equals('com.your_app_package.sms_encrypted_msg')){
      ...
   }
}