From the docs of the Activity
class:
The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().
The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.
The second and third points seem to clearly mention what you're looking for (the onResume()
method). If you're using fragments, the same rules apply. The onResume()
method of the fragment will be called after onResume()
of the activity.
http://developer.android.com/reference/android/app/Activity.html
http://developer.android.com/reference/android/app/Fragment.html#Lifecycle
EDIT :
Well, apparently there is no direct solution to this. I have an idea, but it's more of an improvisation than a proper solution. Also, it may or may not work. Try these things -
- If you're using fragments in a
ViewPager
(with tabs), the FragmentPagerAdapter
will call setUserVisibilityHint(true)
on the currently displayed fragment. You can check for this with getUserVisibilityHint()
in your fragment.
- If you're using a
ScrollView
as a container, maybe you could listen for scroll changes and determine whether your fragment is visible or scrolled out. See this answer for more info.
- For individual widgets, you can check for visibility with
View.isVisible()
.
None of these options provide a definite event-based mechanism to check for visibility, but maybe you can use them somehow. One way would be to define your own callbacks, and override the above methods to call them. Let me know if you get any of these methods (or some other method) to work.