问题
I can call an Activity from a BroadcastReceiver by this way:
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
try {
Intent i = new Intent(context, MyActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Log.v(TAG, "alarm triggered");
} catch (Exception e) {
Log.v(TAG, e.toString());
}
}
}
This brings the app to the front and calls onResume()
at the Activity. My problem is I can't determine if the BroadcastReceiver brought me to onResume()
or just the user itself by hand. Is there any way I can be sure that the BroadcastReceiver called the Activity?
I also tried to fill the Intent at the BroadcastReceiver with Extras by doing i.putExtra("foo", "bar")
. I couldn't read it out by calling MyActivity.getIntent().getExtras().get("foo")
at the Activity.
Hope somebody can help me with this issue, thank you very much!
回答1:
You can send extras in your intent and check them onReceive but proper way of doing this would be to set a boolean value for "STARTED_BY_RECEIVER";
When starting the activity, throw the third line into your onReceive callback method;
Intent i = new Intent(context, MyActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("STARTED_BY_RECEIVER", true);
context.startActivity(i);
Then in the onCreate of the activity, you can check if this was started by the broadcast receiver like this;
if(getIntent().getExtras() != null && getIntent().getExtras().getBoolean("STARTED_BY_RECEIVER")){
// The activity was started by the receiver
}
else{
// The activity was started by user
This would work because the getBoolean method would return false when there's no extra called "STARTED_BY_RECEIVER", this way you only have to put the flag in the one place (started by receiver)
Also don't forget to the put the "STARTED_BY_RECEIVER" in a static variable and use that in both places!
回答2:
Broadcast receivers cant pass extras http://developer.android.com/reference/android/content/BroadcastReceiver.html
You could try to do it in reverse though, have the user action of opening the activity pass a boolean set to true as default value the you can check for
boolean userStarted = getIntent().getExtras().getBoolean('userStarted', false);
来源:https://stackoverflow.com/questions/8596554/start-an-activity-from-a-broadcastreceiver-with-a-result