Android如何在广播接收器中接收短信

时间:2019-01-28 19:18:20

标签: android sms android-broadcastreceiver

我想检测一条消息何时接收日志或Toast号码和消息文本。为此,我在清单中使用SMS_RECEIVED广播,但不起作用。我在lolliphp版本模拟器上尝试了此操作,但没有任何反应。当我调试广播接收器不起作用时,这是我的代码。

manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="clicksource.ir.cameratest">
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_MMS"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".SmsReceiver" android:enabled="true">
            <intent-filter android:priority="0">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
        </receiver>
    </application>

</manifest>


public class SmsReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
      //  if (intent.getAction().equals(SMS_RECEIVED)) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                // get sms objects
                Object[] pdus = (Object[]) bundle.get("pdus");
                if (pdus.length == 0) {
                    return;
                }
                // large message might be broken into many
                SmsMessage[] messages = new SmsMessage[pdus.length];
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < pdus.length; i++) {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    sb.append(messages[i].getMessageBody());
                }
                String sender = messages[0].getOriginatingAddress();
                String message = sb.toString();
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

            }
        }
   // }
}

0 个答案:

没有答案