Missing Extras in Intent when received from a BroadcastReceiver

3.2k Views Asked by At

I have a broadcast receiver which listens for all outgoing calls. In another activity I make an outgoing call. In my BC I want to be able to determine which calls were created in the activity, so I use putExtras() to place a marker field when I'm making the call. Problem is, in the onReceive() of the BC I don't see the extra data field at all (returns null).

Here is the relevant Activity code:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        appGlobal gState = (appGlobal)getApplicationContext();
        dh = gState.getSqlDataHelper();
        Bundle extras = getIntent().getExtras(); 
        if(extras != null)
        {
            phoneNumber = extras.getString("number");
        }
        makePhoneCall();
        finish();
    }

private void makePhoneCall()
    {

        if (phoneNumber.length() < 1) {
            return;
        }
        String url = "tel:" + phoneNumber;
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
        intent.putExtra("number", "bla");

        startActivity(intent);
    }

And here is the relevant BC code:

public class CallMeNotServiceCallReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();

        if (intent.getStringExtra("number") != null)
        { Log.w("bla", "HAS KEY!!!"); }
...

Does this situation require a PendingIntent?

2

There are 2 best solutions below

0
On BEST ANSWER

The official BroadcastReceiver API reference clearly states (3rd paragraph) :

[...] the Intent broadcast mechanism is completely separate from Intents that are used to start Activities. There is no way for a BroadcastReceiver to see or capture Intents used with startActivity(); [...]

So as Jason & HellBoy have suggested, instead of starting an Activity in makePhoneCall(), you send a Broadcast to your BroadcastReceiver, which in turn starts an Activity (only if it contains the marker extra of course)...

3
On

If you add additional logging, do you find that the BroadcastReceiver actually doesn't get called at all?

Use sendBroadcast(intent) to send an Intent that a BroadcastReceiver will receive. You're currently using startActivity which expects an Intent with a particular Activity class to start.