为此,我使用AlarmManager来设置一个PendingIntent,并且这个触发器是BroadcastReceiver.这个BroadcastReceiver然后启动一个Activity来将UI带到前台.
上述所有内容似乎都有效,因为活动正确启动;但是我想要BroadcastReceiver通知“活动”它是由闹钟启动的(而不是由用户启动).为了做到这一点,我正在尝试,从BroadcastReceiver的onReceive()方法在intent的extras bundle中设置一个变量,因此:
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,那么附加功能就会很好.
有没有人可以告诉我将一个bundle从BroadcastReceiver传递到Activity,而不是将bundle从Activity传递给BroadcastReceiver呢?我怕我可能会在这里做一些非常明显的错误
解决方法
在扩展BroadcastReceiver的服务类中.在onReceive()中放入以下代码
Intent intent2open = new Intent(context,YourActivity.class); intent2open.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent2open.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); String name = "KEY"; String value = "String you want to pass"; intent2open.putExtra(name,value); context.startActivity(intent2open);
FLAG_ACTIVITY_SINGLE_TOP确保应用程序已经打开时不会重新打开.这意味着首先打开YourActivity的“旧”意图被重新使用,它不会包含额外的值.你必须用另一个在YourActivity中的onNewIntent()方法来捕获它们.
public class YourActivity extends Activity { private String memberFieldString; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Code doing your thing... } // End of onCreate() @Override protected void onNewIntent(Intent intent) { Log.d("YourActivity","onNewIntent is called!"); memberFieldString = intent.getStringExtra("KEY"); super.onNewIntent(intent); } // End of onNewIntent(Intent intent) @Override protected void onResume() { if (memberFieldString != null) { if (opstartsIntent.getStringExtra(KEY) != null) { Log.d("YourActivity","memberFieldString: "+ memberFieldString); } else { Log.d("YourActivity","The intent that started YourActivity did not have an extra string value"); } } } // End of onResume() } // End of YourActivity
请注意两个if语句 – onResume()不知道是否在OnCreate() – > OnStart()OR onRestart() – > onStart()之后调用.
请参阅:http://www.anddev.org/images/android/activity_lifecycle.png
它只是用来测试应用程序是由用户启动的(意图没有额外的)或BroadcastReceiver(意图与额外的).