Reputation: 7141
Im trying to call a function from within a doInBackground of an AsyncTask
that fades in a progressBar. Everytime i call this function the progressbar fades in as required then disappears. I added a check at the end which tells me that the visibility of the progressbar has returned back to GONE
as soon as the runOnUIThread
method completes:
Reset Prog To Gone
Why is this and how can I make it so the progressbar remains visible?
I have been using the following:
@TargetApi(12)
private void fadeInProgressBar(final int time, ProgressBar prog){
System.out.println("MainActivity: Fading In ProgressBar");
runOnUiThread(new Runnable(){
@Override
public void run() {
if(usingHigherApiThan(12)&&prog.getVisibility()==View.GONE){
prog.setVisibility(View.VISIBLE);
if(prog.getAlpha()<1){
prog.animate().setDuration(time).alpha(1);
}
}else if(prog.getVisibility()==View.GONE){
prog.setVisibility(View.VISIBLE);
final AlphaAnimation animation = new AlphaAnimation(0F, 1F);
animation.setDuration(time);
animation.setFillAfter(true);
prog.startAnimation(animation);
}
}
});
if(prog.getVisibility()==View.VISIBLE){
System.out.println("Left Prog Visible");
}else{
System.out.println("Reset Prog To Gone");
}
}
note usingHigherApiThan(12)
just checks the build version is 12 or greater and this problem occurs for both above 12 and below 11.
Upvotes: 0
Views: 676
Reputation: 44571
You don't need to, and probably shouldn't, do it this way. AsyncTask
has methods that run on the UI
thread already (all but doInBackground()
)
Put your code that you want to run on the UI
into onPostExecute()
to run when doInBackground()
has finished.
Or if it suits your needs better you can also put the code in onProgressUpdate()
and call this function when needed with publishProgress()
.
Alternatively, if you only need it to run when the task starts then you can just put it in onPreExecute()
. All of these run on the UI Thread
. There's no need to add extra steps with runOnUiThread()
.
Upvotes: 1