I am downloading a file from dropbox which is taking a few seconds. I want to add a ProgressDialog for the download but I don't know how to do that.
public class DownloadFile extends AsyncTask<Void, Long, Boolean> {
DownloadFile(Context context ,DropboxAPI<?> mApi ,String dropboxpath,String sdpath,int pos,int s,ArrayList<String> folder) throws DropboxException {
FileOutputStream mFos;
File file=new File(sdpath);
String path = dropboxpath;
try{
mFos = new FileOutputStream(file);
mApi.getFile(path, null, mFos, null);
}catch (Exception e) {
// TODO: handle exception
}
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
Do it this way:
public final class DownloadFile extends AsyncTask<Void, Long, Boolean> {
private Context context;
private ProgressDialog progressDialog;
public DownloadFile (Context context) {
this.context = context;
}
/*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
try {
progressDialog = ProgressDialog.show(context, "", "message", true);
} catch (final Throwable th) {
//TODO
}
}
/*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Boolean doInBackground(Void... arg0) {
//do something
}
#Override
protected void onProgressUpdate(String... progress) {
//do something
super.onProgressUpdate(progress);
}
/*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Boolean result) {
progressDialog.dismiss();
} }
Use this simple code #sachin
public class DownloadFile extends AsyncTask<Void, Void, Void> {
Home home;
ProgressDialog dialog = null;
public DownloadFile(Home home) {
// TODO Auto-generated constructor stub
this.home = home;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//Call hare method for download
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(home, "Downloading......", "", true);
}
}
This article can be useful for you:
http://huuah.com/android-progress-bar-and-thread-updating/
Where inside the run() method of your thread you can invoke a function like this:
public boolean download(String url, String path, String fileName, Handler progressHandler) {
try {
URL sourceUrl = new URL(formatUrl(url));
if (fileName == null || fileName.length() <= 0) {
fileName = sourceUrl.getFile();
}
if (fileName == null || fileName.length() <= 0) {
throw new Exception("EMPTY_FILENAME_NOT_ALLOWED");
}
File targetPath = new File(path);
targetPath.mkdirs();
if (!targetPath.exists()) {
throw new Exception("MISSING_TARGET_PATH");
}
File file = new File(targetPath, fileName);
URLConnection ucon = sourceUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(100);
int current = 0;
int totalSize = ucon.getContentLength();
while ((current = bis.read()) != -1) {
baf.append((byte) current);
// BEGIN - Handler feedback
if (progressHandler != null && (baf.length() % 100) == 0) {
Message msg = progressHandler.obtainMessage();
Bundle b = new Bundle();
if (totalSize > 0) {
b.putInt("total", totalSize);
b.putInt("step", baf.length());
b.putBoolean("working", true);
}
msg.setData(b);
progressHandler.handleMessage(msg);
}
// END
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
// BEGIN - Handler feedback
if (progressHandler != null) {
Message msg = progressHandler.obtainMessage();
Bundle b = new Bundle();
if (totalSize > 0) {
b.putInt("total", 0);
b.putInt("step", 0);
b.putBoolean("working", false);
}
msg.setData(b);
progressHandler.handleMessage(msg);
}
// END
return file.exists();
}
Doing this way, you have a more accurate feedback about real progress of you download (byte per byte).
See there are actually 4 methods of AsyncTask:
onPreExecute() - you can do some pre execution task here.
doInBackground() - you can perform some background work here.
onPostExecute() - you can perform post execution task here. Means like displaying data in ListView, update TextView, etc.
onProgressUpdate() - To update UI while background operation is going on.
So in your case, you can show progress dialog or progress bar inside onPreExecute() method of AsyncTask and dismiss(() the same inside onPostExecute().
Related
Hi in the below downloading images for showing progessbar to 100 but completeld 100% images are not showing still downloading and not showing .i want after 100% i want to move to activity.
But it's taking time to move next activity.
java
public class DownloadTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
final DialogProgressBarRunnable progressDialog =
new DialogProgressBarRunnable(getActivity(), false, 2);
progressDialog.show();
// the dialog box shouldn't get cancelled when clicking outside it or pressing back button.
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
// pd.setMessage("Downloading catalogue images.");
// pd.show();
}
protected String doInBackground(Void... Params) {
parsingObject = new ParsingForFinalImages(catid, responseJson);
/* ConnectionDetector cd = new ConnectionDetector(getActivity().getBaseContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent==true)
{
}
*/
// put your code here
// JSON parsing begins here via the parsing class
// Put this code in async task
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// pd.hide();
// pd.dismiss();
Intent intent = new Intent(getActivity(), ImageGallery.class);
startActivity(intent);
}
}
private class DialogProgressBarRunnable extends ProgressDialog implements
Runnable {
private boolean showSecondary;
private int incrementAfter;
public DialogProgressBarRunnable(Context context,
boolean showSecondary, int incrementAfter) {
super(context);
setCancelable(true);
setMessage(getString(R.string.download_message));
setSecondaryProgress(0);
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
setMax(100);
setProgress(0);
this.showSecondary = showSecondary;
this.incrementAfter = incrementAfter;
}
#Override
public void show() {
super.show();
new Thread(this).start();
}
#Override
public void run() {
while (progress < 100) {
progress++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// increment the first/second progress bar after every %
progressBar();
}
}
private void progressBar() {
if (progress % incrementAfter == 0) {
progressFirstBar();
}
if (showSecondary) {
progressSecondaryBar();
}
}
private void progressSecondaryBar() {
while (secondaryProgress < 100) {
secondaryProgress++;
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
setSecondaryProgress(secondaryProgress);
}
});
}
}
private void progressFirstBar() {
secondaryProgress = 0;
handler.post(new Runnable() {
#Override
public void run() {
setProgress(progress);
if (progress == 100) {
dismiss();
}
}
});
}
}
class DownloadFileFromURL extends AsyncTask {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
// Declear Variables
int count;
try {
URL url1 = new URL(url);
URLConnection conection = url1.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url1.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString() + "/Report.xls");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
Log.d("Downloding"+data,"Count"+count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
#Override
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String reString) {
// dismiss the dialog after the file was downloaded
super.onPostExecute(null);;
dismissDialog(progress_bar_type);
Log.d("Download","Completed");
Intent intent1=new Intent(DownloadExcle.this,MainActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
}
I am writing a code in which I need to move all file and folders to the sdcard. I used Async task for this purpose. During this activity I am showing a progressbar with percentage on my screen instead of just showing me the "Loading..." popup. But it does not meet my requirement.
public class syncMgr extends AsyncTask<String, Long, String> {
public LoginActivity activity;
public Context context;
syncMgr(LoginActivity activity1,Context c)
{
activity = activity1;
context=c;
}
//public ProgressDialog progress;
protected void onPreExecute() {
super.onPreExecute();
activity.progress = ProgressDialog.show(context,"","Files Downloading, Please Wait...",true);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
copyFilesToSdCard();
return null;
}
private void copyFilesToSdCard() {
copyFileOrDir("");
}
private void copyFileOrDir(String path) {
AssetManager assetManager = activity.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() " + path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path=" + fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir " + fullPath);
for (int i = 0; i < assets.length; ++i) {
publishProgress((int) ((i / (float) 658) * 100));
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
copyFileOrDir(p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void publishProgress(int i) {
// TODO Auto-generated method stub
activity.progress.setProgress(i);
}
#Override
protected void onProgressUpdate(Long... values) {
activity.progress.setProgress(values[0].intValue());
}
#Override
protected void onPostExecute(String result) {
activity.progress.dismiss();
super.onPostExecute(result);
//return "asdas";
//return result;
}
}
Here is my Activity Class Code...
ProgressDialog progress;
public static final int progress_bar_type = 0;
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
progress = new ProgressDialog(this);
progress.setMessage("Downloading file. Please wait...");
progress.setIndeterminate(false);
progress.setMax(100);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setCancelable(true);
progress.show();
return progress;
default:
return null;
}
}
Have you tried putting the asyncTask initiation code into a worker thread like this?
// set progressBar .VISIBLE first
// then...
new Thread(new Runnable() {
public void run() {
// webview initiation code
}
}).start();
I turn on progressBar visibility beforehand and not in onPreExecute().
Here is how it solved my own problem & here are the docs.
in the following code I used of onpause and onstop and ondestroy but it is useless and when turn off wifi by user save incomplete file but I want when turn off wifi by user,canceled download.
what can i do?
what should I add in the code?
my code:
public class DoaMatn1 extends Activity implements OnClickListener {
// .
// .
// .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doamatn);
// .
// .
// .
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/EBKH/basem-tavasol.mp3");
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnplaydoa :
// .
// .
// .
case R.id.btndowndoa :
if(!new File(Environment.getExternalStorageDirectory().toString() + "/EBKH/basem-tavasol.mp3").exists())
downloadTask = (DownloadFileFromURL) new DownloadFileFromURL().execute(file_url);
}}
#Override
protected void onStop() {
if(downloadTask!=null){
downloadTask.cancel(true);
}
super.onStop();
}
#Override
protected void onPause() {
if(downloadTask!=null){
downloadTask.cancel(true);
}
super.onPause();
}
#Override
protected void onDestroy() {
if(downloadTask!=null){
downloadTask.cancel(true);
}
super.onDestroy();
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onCancelled() {
File file= new File("/sdcard/EBKH/basem-tavasol.mp3");
file.delete();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream("/sdcard/EBKH/basem-tavasol.mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}}
Taken from this question...
Register a broadcast receiver:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
and receive:
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
boolean connected = info.isConnected();
if (!connected) {
// Stop the download.
}
}
}
This method will detect a change in wifi and if the change is that the wifi is not connected, cancel the download.
Im useing onCancelled() in asynctask for delete incomplete file but when download incomplete file donnt delete it.
(file is music)
why not delete incomplete file in the following code?
my api is 8
this is my code:
public class ZiaratMatn4 extends Activity implements OnClickListener {
MediaPlayer mp;
ImageButton btndownziarat;
ImageButton btnplayziarat;
SeekBar seek_bar;
Handler seekHandler = new Handler();
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private static String file_url = "http://upir.ir/files92be/2eda2a6a5434.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ziaratmatn);
mp = MediaPlayer.create(this,Uri.fromFile(audioFile));
btnplayziarat = (ImageButton) findViewById(R.id.btnplayziarat);
btnplayziarat.setOnClickListener(this);
btndownziarat = (ImageButton) findViewById(R.id.btndownziarat);
btndownziarat.setOnClickListener(this);
getInit();
seekUpdation();
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/EBKH/basem-vares.mp3");
public void getInit() {
if(audioFile.exists())
{
seek_bar = (SeekBar) findViewById(R.id.sbziarat);
seek_bar.setMax(mp.getDuration());
}}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnplayziarat :
if(audioFile.exists())
{
if(mp!=null)
{
if(mp.isPlaying())
{
mp.pause();
btnplayziarat.setImageResource(R.drawable.play);
}
else
{
mp.start();
btnplayziarat.setImageResource(R.drawable.puse);
}}}
break;
case R.id.btndownziarat :
if(!new File(Environment.getExternalStorageDirectory().toString() + "/EBKH/basem-vares.mp3").exists())
new DownloadFileFromURL().execute(file_url);
break;
}}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
if(audioFile.exists())
{
seek_bar.setProgress(mp.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("در حال دانلود،لطفا صبور باشید...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onCancelled() {
File file= new File("/sdcard/EBKH/basem-vares.mp3");
file.delete();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream("/sdcard/EBKH/basem-vares.mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}}}
I am unsure as to what is going on here but what might help is adding a finally{} block at the end which checks if the total bytes read is equal to the length of the file. If not, delete the file.
It's because you're never cancelling the AsyncTask!!! You need to call cancel() on the AsyncTask object, but to do that you need to keep the instance in a variable first.
So first, keep the instance of the AsyncTask, so declare the task in your class
DownloadFileFromURL downloadTask;
When you create the task, assign it to your variable
downloadTask = new DownloadFileFromURL().execute(file_url);
And whenever you want to cancel, call this:
downloadTask.cancel();
Dear Stackoverflowians
I have a Gridview, In that each item is having horizontal progress bar set visible on item button click
i do it by using asyncTask it works,but, Now my Problem is
1) when ever i scroll up or down while progressing, Progressbar progress in visible other item regarding position change
2) changing activity and came again to this activity the progress bar is not visible in that grid item but progress running in backgroud i check it in Logcat.
Here the sample of my process
Here is the code of that progress download
private void UpdateDB(String strFilename,int lintIssueId,boolean bPreview,ImageView btnDownload,ImageView btnView)
{
try{
btnDownload.setVisibility(View.GONE);
btnView.setVisibility(View.VISIBLE);
}catch(Exception ex){}
}
private static class SCSDownload extends AsyncTask<String, Integer, String>
{
Main_Page activity;
MiddlewareInterface AMI=MiddlewareInterface.GetInstance();
ProgressBar mProgressbar;
RelativeLayout mRtProgress;
ImageView btnDownload,btnView;
int issueid;
boolean bPrev;
Context context;
SCSDownload(Main_Page act,ProgressBar mProgressbar,RelativeLayout mRtProgress,ImageView btnDownload,ImageView btnView,int issueid,boolean bPrev)
{
this.mProgressbar=mProgressbar;
this.mRtProgress=mRtProgress;
this.issueid=issueid;
this.bPrev=bPrev;
this.btnView=btnView;
this.btnDownload=btnDownload;
attatch(act);
}
void attatch(Main_Page act)
{
activity=act;
context=act;
}
void detatch()
{
activity=null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mRtProgress.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if(result!=null)
{
try{
if(mRtProgress!=null)
mRtProgress.setVisibility(View.GONE);
activity.UpdateDB(result,issueid,bPrev,btnDownload,btnView);
}catch(Exception e){}
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
mProgressbar.setProgress(values[0]);
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
String File_Name=params[0].substring( params[0].lastIndexOf('/')+1, params[0].length() );
File file = new File(context.getDir(AMI.strMainDir, Context.MODE_PRIVATE) + "/"+File_Name);
if (!file.exists())
{
file.createNewFile();
URL url=new URL(params[0]);
URLConnection con=url.openConnection();
con.connect();
int LengthOfFile=con.getContentLength();
InputStream input=new BufferedInputStream(url.openStream());
OutputStream output=new FileOutputStream(file);
byte data[]=new byte[1024];
int count = 0;
long total=0;
while((count=input.read(data))!=-1&&(!isCancelled()))
{
total+=count;
Log.d("total",total+"");
publishProgress((int)((total*100)/LengthOfFile));
output.write(data,0,count);
}
output.flush();
output.close();
input.close();
}
return File_Name;
}catch(Exception ex){}
return null;
}
}