如何在Android Studio中使用广播接收器接收SMS?

时间:2019-04-24 22:40:52

标签: java android broadcastreceiver

我正在构建一个应在收到SMS时触发功能的应用程序。我以前使用过广播接收器和NotificationListeners,但是出于此特定目的,我需要注册此广播接收器。目前,我无法注册,也无法确定原因。

我已经尝试了关于堆栈溢出的类似问题的多个答案,但是由于某些原因,当我收到SMS时,我现在用来进行故障排除的Log.d将不会打印。尽管我不确定如何,但我认为我从根本上误解了这个问题。

这是我的SmsListener.java班:

public class SmsListener extends BroadcastReceiver {
    private SharedPreferences preferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Log.d("Test","test");
        }
    }
}

这是我的清单:

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

这里是我的活动的onCreate()函数,应调用它:

BroadcastReceiver br = new SmsListener();
IntentFilter filter = new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
registerReceiver(br,filter);

谢谢您的帮助。我无所适从。

1 个答案:

答案 0 :(得分:0)

这是您的接收器类-

private static final String SMS_RECEIVED =“ android.provider.Telephony.SMS_RECEIVED”;     私有静态最终字符串TAG =“ SMSBroadcastReceiver”;

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

    if (intent.getAction() != null) {
        if (intent.getAction().equals(SMS_RECEIVED)) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                final SmsMessage[] messages = new SmsMessage[pdus.length];
                for (int i = 0; i < pdus.length; i++) {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    Log.e("Message Content : ", " == " + messages[i].getMessageBody());
                    Log.e("Message Content Body : ", " == " + messages[i].getDisplayMessageBody());
                    Log.e("Message recieved From", " == " + messages[0].getOriginatingAddress());
                }
            /*if (messages.length > -1) {
                Log.e("Message recieved: "," == "+ messages[0].getMessageBody());
                Log.e("Message recieved From"," == "+ messages[0].getOriginatingAddress());
            }*/
            }
        }
    }
}