Search code examples
androidbroadcastreceiverautostart

How to pass value from BroadcastReceiver to main activity


I want to tell my MainActivity, that it is starting automatically by BroadcastReceiver when boot is completed. It seems to be possible to send over putExtra some values to the MainActivity like this:

public class StartAppAtBootReceiver extends BroadcastReceiver {

private static final String key_bootUpStart = "bootUpStart";
private static boolean bootUpStart = true;

@Override
public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {

        Intent activityIntent = new Intent(context, MainActivity.class);
        activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activityIntent.putExtra(key_bootUpStart, bootUpStart);
        context.startActivity(activityIntent);

    }
}
}

But how can I receive that value inside my MainActivity?


Solution

  • On the BroadcastReceiver you send the intent to the Activity.

    I modified your key to be public so that you can reuse it.

    public static final String KEY_BOOTUP_START = "bootUpStart";
    

    On the Activity you process the Intent.

    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        processExtraData();
    }
    
    protected void onNewIntent(Intent intent) 
    {
        super.onNewIntent(intent);
        setIntent(intent);
        processExtraData()
    }
    
    private void processExtraData()
    {
        Intent intent = getIntent();
        // Use the data here.
        boolean value = getIntent()
            .getBooleanExtra(StartAppAtBootReceiver.KEY_BOOTUP_START, false);
    }