onReceive不适用于传入短信

时间:2014-12-08 11:49:07

标签: android sms

我有一个问题是捕获到达设备的新SMS消息

为BroadcastReceiver创建一个单独的类

public class SmsListener extends BroadcastReceiver {

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

    // Retrieves a map of extended data from the intent.
    final Bundle bundle = intent.getExtras();

    try {

        if (bundle != null) {

            final Object[] pdusObj = (Object[]) bundle.get("pdus");

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

                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                String senderNum = phoneNumber;
                String message = currentMessage.getDisplayMessageBody();

                Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);

                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
                toast.show();

            } // end for loop
        } // bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" +e);

    }
}

并在清单

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

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

并且不要在Main class

添加任何代码

问题是我收到短信但没有Log或Toast。 需要主要的任何意图吗?谢谢

1 个答案:

答案 0 :(得分:0)

您应该使用@Override标记onReceive方法。

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