I have a long running io process that I would like to be able to set a progress bar during to show that there is in fact a process running and the app isn’t just frozen. The process copies over many music files, and can take upwards of a minute depending on how many are available.
The problem is, it seems to be executing the code before setting the progress bar visibility.
public void makeAvailable() {
mProgressBar.setVisibility(View.VISIBLE);
File dir = new File(gMusic);
String[] songNames = dir.list();
File[] songs = dir.listFiles();
for (int i=0; i<songs.length; i++) {
File song = songs[i];
String songName = songNames[i];
String[] bits = songName.split("/");
String songStripped = bits[bits.length-1];
File output = new File(Constants.gMusicSniperDir + "music/" + songStripped);
try {
copyFile(song, output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mProgressBar.setVisibility(View.INVISIBLE);
}
As you see, it cycles through the directory and copies all the files over. When it runs, the only indication of anything happening is that the button that is tied to the process doesn’t leave the “pressed” state – it stays highlighted blue.
It looks like you’re doing all your work in the UI thread. You should do all the heavy work (listing the contents of the directory, and copying files) in a background thread, posting requests to the UI thread just to update the progress bar.
The
ProgressBardocumentation gives an example of this.Note that this is just one example of a common theme: you shouldn’t block the UI thread for any significant length of time, or your application will become unresponsive. See “Designing for Responsiveness” for more details.