我有一个 Android 应用程序需要全天偶尔唤醒。
为此,我使用 AlarmManager 来设置 PendingIntent 并让它触发一个 BroadcastReceiver。然后此 BroadcastReceiver 启动一个 Activity 以将 UI 带到前台。
以上所有似乎都有效,因为 Activity 正确启动了自己;但我希望 BroadcastReceiver 通知 Activity 它是由警报启动的(而不是由用户启动的)。为此,我正在尝试从 BroadcastReceiver 的 onReceive() 方法在意图的附加包中设置一个变量,因此:
Intent i = new Intent(context, MyActivity.class);
i.putExtra(wakeupKey, true);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
在我的 Activity 的 onResume() 方法中,我然后寻找这个布尔变量的存在:
protected void onResume() {
super.onResume();
String wakeupKey = "blah";
if (getIntent()!=null && getIntent().getExtras()!=null)
Log.d("app", "onResume at " + System.currentTimeMillis() + ":" + getIntent().getExtras().getBoolean(wakeupKey));
else
Log.d("app", "onResume at " + System.currentTimeMillis() + ": null");
}
onResume() 中的 getIntent().getExtras() 调用始终返回 null - 我似乎无法在此捆绑包中传递任何额外内容。
但是,如果我使用相同的方法将额外内容绑定到触发 BroadcastReceiver 的 PendingIntent,那么额外内容就可以了。
谁能告诉我将包从广播接收器传递到活动与将包从活动传递到广播接收器有什么不同?我担心我可能在这里做一些非常明显的错误......