简体   繁体   English

Android:将值从活动传递到broadcastreceiver

[英]Android: Pass value from activity to broadcastreceiver

First of all, sorry for my bad grammar. 首先,抱歉我的语法不好。 I am developing Auto Reply Message Application using broadcastreceiver i have problem with when I can receive value from activity to broadcastreceiver, the Auto Reply won't work. 我正在使用broadcastreceiver开发自动回复消息应用程序我有问题,当我可以从活动接收值到broadcastreceiver时,自动回复将无法正常工作。 But if I'm not receive value from Activity, it's working. 但是,如果我没有从Activity获得价值,它就会起作用。 this is my activity code, I put it in onSensorChanged() 这是我的活动代码,我把它放在onSensorChanged()

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

and this is my broadcastreceiver class 这是我的广播接收班

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);
        }
    }
}

and this is my manifest 这是我的表现

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

The action will never be both android.provider.Telephony.SMS_RECEIVED and my.action.string . 该动作永远不会同时是android.provider.Telephony.SMS_RECEIVEDmy.action.string

Change this: 改变这个:

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

To this: 对此:

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

In addition, you're not sending pdus in the manually created Intent, so when you call bundle.get("pdus") it will return null. 此外,您不是在手动创建的Intent中发送pdus ,因此当您调用bundle.get("pdus") ,它将返回null。 Then when you call pdus.length it will throw a NullPointerException. 然后,当您调用pdus.length ,它将抛出NullPointerException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM