Reputation: 239
My app contained download button and whenever that button is pressed, I want some Progress Bar to show up so that the user knows there is something happening. What I really want to do is, whenever the Progress Bar is finished, I want some Toast to pop out. Can some one guide me with this? I would really appreciate it a lot. Thanks in advance!
Here is the code I am using:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ProgressDialog dialog = new ProgressDialog(MyActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("Downloading...");
dialog.setCancelable(true);
dialog.setMax(200);
dialog.setProgress(0);
dialog.show();
Thread t = new Thread(new Runnable(){
public void run() {
while(dialog.getProgress() < dialog.getMax())
{
dialog.incrementProgressBy(1);
try{Thread.sleep(50);}catch(Exception e){/* no-op */}
}
dialog.dismiss();
}
});
t.start();
}
Upvotes: 0
Views: 891
Reputation: 877
You cannot run long tasks on UI thread. Create a background thread with Async Task but you cannot do a toast in a background thread.
Async task will notify when the task is complete.
I think Async task has the following methods.
onBackground onProgressUpdate PreExecute PostExecute (put a toast here)
Upvotes: 0
Reputation: 4256
AsyncTask would be the easiest but if you are adamant on using your code you can add this snippet after the dialog.dismiss() statement.
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(YourClassName.this, "task finished", Toast.LENGTH_LONG).show();
}
});
This is because the Toast must only be shown on the UI Thread.
Upvotes: 1
Reputation: 15477
After dialog.dismiss(); write
Toast.makeText(getApplicationContext(),"finish",Toast.LENGTH_LONG).show();
Upvotes: 0
Reputation: 54322
This can be done using AsyncTask in android. Here are few links which will be handy.
http://sites.google.com/site/androidhowto/how-to-1/asynctasks-with-progressdialogs
http://www.codeproject.com/KB/android/asynctask_progressdialog.aspx
http://javatech.org/2011/02/discovering-android-opening-a-progress-dialog-with-asynctask/
http://www.softwarepassion.com/android-series-download-files-with-progress-dialog/
Upvotes: 0