首先,对我的语法不好感到抱歉。我正在使用broadcastreceiver开发自动回复消息应用程序,但是当我可以从活动接收到Broadcastreceiver的值时遇到问题,自动回复将不起作用。但是,如果我没有从Activity那里获得价值,那就行得通。这是我的活动代码,我将其放在onSensorChanged()中

Intent i = new Intent("my.action.string");
i.putExtra("apaan", lala);
sendBroadcast(i);


这是我的广播接收器类

public class AutoReply extends BroadcastReceiver{

private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Log.i("message", "Broadcast Received: " +action);

    if (action.equals(SMS_RECEIVED) && action.equals("my.action.string")) {
        Bundle bundle = intent.getExtras();
        String state = bundle.getString("apaan");

        if (bundle != null) {
            Object[] pdus = (Object[]) bundle.get("pdus");
            final SmsMessage[] sms = new SmsMessage[pdus.length];
            String isiSMS = "", noPengirim = "";
            for (int i = 0; i < pdus.length; i++) {
                sms[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                isiSMS = sms[i].getMessageBody();//mengambil isi pesan dari pengirim
                noPengirim = sms[i].getOriginatingAddress();//mengambil no pengirim
            }

            String message = state;//isi balasan autoreplay

            SmsManager smsSend = SmsManager.getDefault();
            smsSend.sendTextMessage(noPengirim, null, message, null, null);
        }
    }
}


这是我的清单

<receiver android:name=".AutoReply" android:enabled="true">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            <action android:name="my.action.string" />
        </intent-filter>
</receiver>

最佳答案

该操作永远不会同时是android.provider.Telephony.SMS_RECEIVEDmy.action.string

更改此:

if (action.equals(SMS_RECEIVED) && action.equals("my.action.string")) {


对此:

if (action.equals(SMS_RECEIVED) || action.equals("my.action.string")) {


此外,您不会在手动创建的Intent中发送pdus,因此,当您调用bundle.get("pdus")时,它将返回null。然后,当您调用pdus.length时,它将抛出NullPointerException。

09-11 17:55