How to pass Extra to BroadcastReceiver, when initi

2019-04-10 01:26发布

问题:

I'm initiating new call from my activity. And trying to pass a boolean extra.

public class CallInitiatingActivity extends Activity {

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

        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
        intent.putExtra("com.demoapp.CUSTOM_CALL", true);
        startActivity(intent);
    }
}

I also have a BroadcastReceiver registered, which listens for outgoing calls:

<receiver android:name=".OutgoingCallListener" android:exported="true" >
    <intent-filter android:priority="0" >
        <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

Basically what I'm expecting onReceive to see my extra, but somehow it is not passed:

public class OutgoingCallListener extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();

        for (String key : extras.keySet()) {
            Log.i(Constant.LOG_TAG, key + ": " + extras.get(key));
        }
    }
}

Output:

android.phone.extra.ALREADY_CALLED:false
android.intent.extra.PHONE_NUMBER:+370652xxxxx
com.htc.calendar.event_uri:null
android.phone.extra.ORIGINAL_URI:tel:+370652xxxxx

回答1:

Your custom extra is present in the Intent that you use to start the "call" activity. But it isn't copied into the NEW_OUTGOING_CALL Intent that is broadcast as a part of the actual call mechanism. These 2 operations are distinct and only indirectly related to each other. Only the Android system itself can broadcast the NEW_OUTGOING_CALL Intent.

You can't add your own extras to this Intent. You'll need to come up with another way to do whatever it is you are trying to accomplish.