Search code examples
androidandroid-intentbroadcast

How to get access to intent values from static class broadcastreceiver?


Is it possible to start an intent to another activity from broadcastreceiver scope?

For example, I get an answer from an intentservice with a string as putExtra value in the broadcast. Now I want to assign this string to a local variable in the activity, which received the broadcast or start an intent from the broadcast scope of the receiving activity to another activity with a putExtra containing the received value from the broadcast of the intentservice.

Can anyone tell me, what would be the preferd way to do this?


Solution

  • Yes. You can use intent.getExtras() in the onReceive() callback of your BroadcastReceiver to get access to whatever was sent with putExtra

    You can then build a new Intent to start an activity. Don't forget to add FLAG_ACTIVITY_NEW_TASK flag if you are starting the activity from a non-activity context. You can also copy all the extras from the broadcast:

    @Override void onReceive(Context context, Intent intent) {
        String arg = intent.getExtras().getString("the key used in putExtra");
        // do something with the argument
    
        //or, launch an activity and pass that argument
        Intent activityIntent = new Intent(context, YourActivity.class);
        intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        activityIntent.putExtras(intent.getExtras());
        context.startActivity(activityIntent);
    }