使用BroadcastReceiver检测传入的SMS不起作用

时间:2014-10-02 16:29:07

标签: android sms broadcastreceiver

我正在开发一款Android应用程序,即使我的应用程序关闭,它也会检测并扫描SMS的内容。我知道BroadcastReceiver是解决方案,我已经开发了代码,但遗憾的是没有按预期获得输出。

这是我的活动文件

public class SMSBroadcastReceiver extends BroadcastReceiver {

private static final String TAG = SMSBroadcastReceiver.class.getSimpleName();
public static final String SMS_CONTENT = "sms_content";

@Override
public void onReceive(Context context, Intent intent) {
    Log.i(TAG, "Intent recieved: " + intent.getAction());

    Cursor c = context.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
    c.moveToFirst();
    String smsBody = c.getString(12);
    Toast.makeText(context, "SMS RECEIVED:", Toast.LENGTH_LONG).show();
    Toast.makeText(context, smsBody, Toast.LENGTH_LONG).show();
    }
}

我还在我的Manifest中包含了这些行

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>

<receiver android:name=".SMSBroadcastReceiver">
<intent-filter>
   <action android:name="android.provider.telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>

如何找出出现问题的原因以及为什么我无法向收到的短信致敬?

2 个答案:

答案 0 :(得分:0)

在onReceive方法中,您应该执行类似以下代码的操作来阅读短信内容:

if (intent != null && intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs;
    String sender;
    if (bundle != null) {
        try {
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i = 0; i < msgs.length; i++) {
                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                // Here you have the sender(phone number)
                sender = msgs[i].getOriginatingAddress();
                String msgBody = msgs[i].getMessageBody();
                // you have the sms content in the msgBody
            }
        } catch (Exception e) {
           e.printStackTrace();
     }
 }

这有帮助吗?

答案 1 :(得分:-1)

实际上,唯一的问题是我没有在任何地方开始广播。我刚添加了行

sendBroadcast(new Intent(MyActivity.this, SMSBroadcastReceiver.class));