vladimir
vladimir

Reputation: 733

Android: pass variables from Activity to BroadcastReceiver

I have some problem with passing throught my variable from Activity to the BroadcastReceiver... Here is my code:

here is my Broadcast receiver code... I try to catch SMS from one phone number which I have got from my Activity...

public class SMSMonitor extends BroadcastReceiver 
{
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
    public static String phone_number = "";
    public static String msg_body = "";
    public static final String SMS_EXTRA_NAME = "pdus";

    @Override
    public void onReceive(Context context, Intent intent)
    {
        String phone = intent.getExtras().getString("trusted_num");

        if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0)
        {
            Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
            SmsMessage[] messages = new SmsMessage[pduArray.length];

            for (int i = 0; i < pduArray.length; i++)
            {
                messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
            }

            phone_number = messages[0].getDisplayOriginatingAddress();
            msg_body = messages[0].getMessageBody();

            System.out.println("Phone number: "+phone_number);
            System.out.println("Phone entered: "+phone);
        }
    }
}

Here is my Activity code:

public class Settings extends Activity implements OnClickListener{

    private Button btn_save;
    private EditText txt_phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        //set Save button
        btn_save = (Button)findViewById(R.id.btn_save);
        txt_phone = (EditText)findViewById(R.id.et_phone);

        btn_save.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_settings, menu);
        return true;
    }

    @Override
    public void onClick(View v) 
    {
        if (v == btn_save)
        {
            try
            {
                String phone_num = txt_phone.getText().toString();
                Intent i = new Intent(Settings.this, SMSMonitor.class);
                i.putExtra("trusted_num", phone_num);
                sendBroadcast(i);
            }
            catch(Exception e)
            {
                System.out.println("Error: "+e.getLocalizedMessage());
            }
        }
    }

}

In this code I have text field for entering the phone number, which I need to pass to the BroadcastReceiver with intent.putExtra() method, but in LogCat I see, that variable didnot pass:

07-25 18:43:57.382: I/System.out(14245): Phone number: +37129690449
07-25 18:43:57.382: I/System.out(14245): Phone entered: null

So what I am doing wrong here?

UPD Maybe code is not correct, but it works for me...

public void onReceive(Context context, Intent intent)
    {
        phone = intent.getExtras().getString("trusted_num");//get trusted phone number from Settings screen

        //receive SMS
        if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0)
        {
            Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
            SmsMessage[] messages = new SmsMessage[pduArray.length];

            for (int i = 0; i < pduArray.length; i++)
            {
                messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
            }

            phone_number = messages[0].getDisplayOriginatingAddress();
            msg_body = messages[0].getMessageBody();

            System.out.println("Phone number: "+phone_number);
        }
        //check if number is not null
        if (phone != null && phone != "")
        {
            System.out.println("Phone entered: "+phone);
        }

    }
}

Upvotes: 1

Views: 2090

Answers (2)

gunar
gunar

Reputation: 14710

Well, there are some things not that don't match:

You're sending an intent with no action in the first place, but you're specifying Broadcastreceiver's class; don't do like that:

Intent i = new Intent(Settings.this, SMSMonitor.class);
i.putExtra("trusted_num", phone_num);
sendBroadcast(i);

But try instead:

Intent i = new Intent("my_package_name.Some_general_constant");
i.putExtra("trusted_num", phone_num);
sendBroadcast(i);

Then, your BroadcastReceiver is supposed to know that it can also handle "Some_general_constant" action. For this reason, register an extra action in your Manifest file for your SMSMonitor:

<receiver android:name=".package_to_bla_bla.SMSMonitor">
    <intent-filter>
        <action android:name="my_package_name.Some_general_constant"/>
    </intent-filter>
</receiver>

Then in your SMSMonitor you need to add an else if statement to handle this broadcast:

else if("my_package_name.Some_general_constant".equals(intent.getAction()) 
    {
         // get the data from intent and use it 
    }

Upvotes: 0

Shmuel
Shmuel

Reputation: 3916

You can't pass an intent to a broadcast receiver. "There is no way for a BroadcastReceiver to see or capture Intents used with startActivity()" https://developer.android.com/reference/android/content/BroadcastReceiver.html

I had a similar issue a while back and solved it by using a combination of IntentServices and Activities. You have to restructure your program to fit these guidlines

Upvotes: 1

Related Questions