I have the following situation:
I have an Activity
that hosts a ViewPager
, and I have 4 Fragments
;
the ViewPager
It seems easy to me,what you need is Fragments onResume() method
. This will be called only when your fragment is VISIBLE to user.
Here you can add logic to initiate your network call. It guarantees that your fragment is in visible mode.
See this
However you can optimize your network calls logic, using LoaderManager with AsyncTaskLoader pattern.
Loaders take care of screen orientation changes & they cache data for you. So that network call is not initiated twice for same operation.
From Android documentation
Introduced in Android 3.0, loaders make it easy to asynchronously load data in an activity or fragment. Loaders have these characteristics:
They are available to every Activity and Fragment. They provide asynchronous loading of data. They monitor the source of their data and deliver new results
when the content changes. They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.
You can use any Asynchronous HTTP lib for network calls like Retrofit
i found one tutorial for AsyncTaskLoader & LoaderManager @ this link, below are some quotes from tutorial
Loaders aren't trivial, so why use them in the first place? Well, in most cases, you would use them in the same scenarios where you've been using AsyncTasks; in fact, some loader subclasses extend AsyncTask. Just as AsyncTasks are used to perform any long-running operation that would tie up the user thread and ultimately throw the dreaded Application Not Responding (ANR), loaders perform in the same manner with the same purpose. The main difference is loaders are specialized for loading data. As such, loaders offer a number of efficiency and convenience benefits.