views:

116

answers:

3

I would like to launch an intent when any of my activity is visible, otherwise I will put it up as a notification, and will be fired by the user.

To decide this, I need to know if any of my activity is front-most, how do I that?

A: 

Based on http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle , I assume you should rely on onStart and onStop to determine when your activity is visible.

cristis
So this involves tracking all the activities individually, isn't there a more lightweight way to tell?
Pentium10
I don't think there is, since you can't get the currently top-most activity.
cristis
+1  A: 

I don't know that there's a method to get the currently displayed activity, but you could do something combining the Activity Lifecycle and a flag.

For the flag, if you've extended the Application class, that's probably a decent place to store it. For extending the application class, the top answer to this question has info. (d).

So probably keep track of the current active activity (or a flag that the activity is visible) in onResume/onPause or onStart/onStop depending on exactly what behavior you want.

Since you have multiple activities, you'll need a centroid place for storing the flag, which is why the Application makes sense. You can get the custom Application object by casting the application context (e.g. ((MyApplication)getApplicationContext()).isMyActivityActive).

You could extend Activity as well to help keep this code clean and contained.


If you're using a service you could bind to the service in every activity in the onStart/onStop (or onResume/onPause). If bound, you're visible.

ydant
+1  A: 

onResume() called && onPause() not called = visible.
Have a public static Activity currentlyVisible; in your Application subclass that will be updated by your activities (set to the instance in onResume() and nulled in onPause()). Or invent a less ugly variant of a registry.

alex
You should not hold references to the activity object like that... see http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html.
cristis
Generally speaking - yes. Unless you null references manually before it's too late.
alex