Reputation: 45931
I'm developing an Android 3.1 application.
I want to execute an AsyncTask
after activity is shown. I want to show something to user before execute AsyncTask
.
I've read that it is not recommend to execute AsyncTask
on onCreate()
.
Where I have to execute AsyncTask
on onStart()
or onResume()
?
I want to left enough time to show activity before execute it.
Upvotes: 3
Views: 3630
Reputation: 34301
Answer is in onResume()
I hade same requirement in my activity where i need to show some list with other buttons and images.. List were getting data from server so used AsyncTask for that..
But before that required to show empty listview and other part of the screen..
so first when it goes to onCreate()
I set empty arraylist
to listview's adapter then in onResume()
call the Asynctask and in that task fill the ArrayList and call adapter.notifyDataSetChanged()
Then another problem occure..when i go to next activity and come back it always call the asynctask even if i dont require..
So had put some condition like if(arrayList.size()==0)
then call asynctask else
dont.
Upvotes: 1
Reputation: 1439
You can put yur code in the onWindowsFocusChanged method. You can use a thread inside it to manage the timer to start your specific asynctask. Be aware that this would be performed each time your activity have the focus, not only the first time you launch your activity (I don't know if this could be a problem for you).
Upvotes: 0
Reputation: 25864
onCreate()
, onStart()
and onResume()
are lifecycle methods called by the operating system and shouldn't be called directly. You can however override them to have your code executed at these stages of the activities lifecycle:
However, if you want your AsyncTask to start after all of your View
s have been inflated and drawn to the screen then you need to put the code in this:
toReturn.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
toReturn.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// asyncTask.execute();
}
});
In the above example toReturn
is a view in your onCreate() method. It can be any view you like.
This pulls a ViewTreeObserver
from the View and add's a listener to it which will be called when the view has finished being drawn to the screen. It's important you keep the "removeGlobalOnLayoutListener()` line in as this will stop the code firing every time the View is drawn.
Upvotes: 11
Reputation: 755
implement a View
object and override the onDraw()
.
that way you'll know exactly when the first screen is visible to the user
Upvotes: -2