如何将值从BroadcastReceiver传递给主要活动

时间:2017-09-07 18:47:57

标签: android broadcastreceiver autostart

我想告诉我的MainActivity,它在启动完成后由BroadcastReceiver自动启动。似乎可以通过putExtra将一些值发送到MainActivity,如下所示:

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);

    }
}
}

但是我怎样才能在MainActivity中获得这个价值?

2 个答案:

答案 0 :(得分:0)

BroadcastReceiver上,您将意图发送到Activity

我将您的密钥修改为公开,以便您可以重复使用它。

public static final String KEY_BOOTUP_START = "bootUpStart";

Activity处理意图。

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);
}

答案 1 :(得分:0)

在您的活动中,您可以获得启动您的活动的意图,如: 在onCreateActivity中:
Intent intent = getIntent();

比:

Object value = intent.getExtra("key_bootUpStart");