Android progress bar is used to determine the progress of a particular task like uploading or downloading a file from the internet. This feature was added in API Level 1. You can create the Android progress bar by using ProgressDialog class. However, you need to instantiate an object of this class.
The logic in progress bar is: using a “Thread” to run your task and another “Thread” to update the progress bar status accordingly. Here, we are going to explain you about the creation of progress bar in Android applications.
First, create MainActivity.java under src/<your packagename>.
MainActivity.java:
[java]
public class MainActivity extends Activity {
Button download;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private long fileSize = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set activity content to external view
setContentView(R.layout.activity_main);
//find views by Id
download = (Button) findViewById(R.id.button1);
//on click download
download.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// creating progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar and file size status
progressBarStatus = 0;
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus = 100) {
// sleeping for 1 second after operation completed
try {
Thread.sleep(1000);
} catch (InterruptedException e) {e.printStackTrace();}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}//end of onClick method
});
}
// checking how much file is downloaded and updating the filesize
public int doOperation() {
//The range of ProgressDialog starts from 0 to 10000
while (fileSize <= 10000) {
fileSize++;
if (fileSize == 1000) {
return 10;
} else if (fileSize == 2000) {
return 20;
} else if (fileSize == 3000) {
return 30;
} else if (fileSize == 4000) {
return 40;
} else if (fileSize == 5000) {
return 50;
} else if (fileSize == 6000) {
return 60;
}
else if (fileSize == 7000) {
return 70;
}
else if (fileSize == 8000) {
return 80;
}
else if (fileSize == 9000) {
return 90;
}
else if (fileSize == 10000) {
return 100;
}
}//end of while
return 100;
}//end of doOperation
}
[/java]
Create activity_main.xml in res/layout folder.
activity_main.xml:
[xml]
[/xml]
AndroidManifest.xml:
[xml]
[/xml]
Output: