Android: How to start a new activity, but only if it already exists?
I am using Android-C2DM, and when I receive a message that has been pushed to my device I want to either update a display (if a certain Activity is visible on the screen) or create a status bar notification (if not).
Everything works besides checking whether or not the Activity is active. What I am lo开发者_开发百科oking for is either a way to check if an Activity is active (then I can just surround the code below with an if
statement), or if that's not possible I guess I need a different way to go about the whole process.
In C2DMBaseReceiver:
Intent i = new Intent(context, Show.class);
i.putExtra("id", id);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
In Show.java:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.v(TAG, "onNewIntent");
// Update the display
}
Have a global that points to the activity that wants to find out about the message. In your activity, set this while you are on the screen (resumed). In your receiver, call the activity if it is set, otherwise put up your notification in the status bar.
You can do more formal implementations of this pattern, but just using a global is simple and for most cases sufficient.
精彩评论