Android Programming Tutorials

(Romina) #1
Sitting in the Background

setProgressBarVisibility(true);
progress= 0 ;
new Thread(longTask).start();

return(true);
}

return(super.onOptionsItemSelected(item));
}

Notice the extra line that makes progress visible.


Then, we need to update the progress bar on each pass, so make this


change to doSomeLongWork():


private void doSomeLongWork(final int incr) {
runOnUiThread(new Runnable() {
public void run() {
progress+=incr;
setProgress(progress);
}
});

SystemClock.sleep( 250 ); // should be something more useful!
}

Notice how we use runOnUiThread() to make sure our progress bar update


occurs on the UI thread.


Finally, we need to hide the progress bar when we are done, so make this


change to our longTask Runnable:


private Runnable longTask=new Runnable() {
public void run() {
for (int i= 0 ;i< 20 ;i++) {
doSomeLongWork( 500 );
}

runOnUiThread(new Runnable() {
public void run() {
setProgressBarVisibility(false);
}
});
}
};

74
Free download pdf