【问题标题】:Detecting incoming SMS using BroadcastReceiver not working使用 BroadcastReceiver 检测传入的 SMS 不起作用
【发布时间】:2018-10-12 22:27:27
【问题描述】:

我正在开发一个 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();
    }
}

我也在我的清单中包含了这些行

<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>

如何找出问题所在以及为什么我无法 Toast 传入的 SMS?

【问题讨论】:

  • Telephony 需要在清单中的 "android.provider.telephony.SMS_RECEIVED" 中大写。也就是说,它应该是"android.provider.Telephony.SMS_RECEIVED"。另外,请注意,当您收到此广播时,新消息可能尚未写入 Provider。

标签: android sms broadcastreceiver


【解决方案1】:

在您的 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();
     }
 }

这有帮助吗?

【讨论】:

  • 嘿迈克!正如你所说,我对我的代码进行了更改,但它仍然不起作用......另外,你能解释一下如何检查新消息是否正在广播中写入提供者???
  • 仅供参考 createFromPdu() 已被弃用。保重
【解决方案2】:

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

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

【讨论】:

  • 我不明白这个答案 - 您没有尝试向您的设备发送短信来测试您的接收器吗??
猜你喜欢
  • 1970-01-01
  • 2020-03-06
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
相关资源
最近更新 更多