I wish to pause the file download at a particular point and add some bytes of data to it and then resume the download. How do I do it?
Below is a code snippet showing what I am downloading :-
private void startDownload() {
String url = "http://coderzheaven.com/sample_folder/sample_file.png";
new DownloadFileAsync().execute(url);
}
Now, below is the DownloadFileAsync class
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Length of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"downloaded_file.png");
OutputStream output = new FileOutputStream(file);
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) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
connection.setRequestProperty("Range", "bytes=" + ***downloaded*** + "-");
Make "downloaded" as global variable, because download start from this position.
when you press on restart button, check value of this downloaded variable,must not zero all time.
Please change the things in below code
public class DownloadWithProgressActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn, pauseButton, resumeButton;
private ProgressBar bar;
URLConnection conexion;
OutputStream output;
static int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button) findViewById(R.id.startBtn);
pauseButton = (Button) findViewById(R.id.button1);
resumeButton = (Button) findViewById(R.id.button2);
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setVisibility(ProgressBar.INVISIBLE);
bar.setId(0);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
resumeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// not getting what to write here
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String doInBackground(String... aurl) {
int downloaded = 0;
File file = new File("/sdcard/some_photo_from_gdansk_poland.jpg");
URL url = null;
try {
url = new URL(aurl[0]);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conexion = url.openConnection();
if (file.exists()) {
downloaded = (int) file.length();
conexion.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
else {
conexion.setRequestProperty("Range", "bytes=" + downloaded
+ "-");
}
} catch (Exception exception1) {
}
conexion.setDoInput(true);
conexion.setDoOutput(true);
System.out.println(tryGetFileSize(url));
conexion.setRequestProperty("Range", "bytes=" + count + "-");
try {
conexion.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = null;
try {
input = new BufferedInputStream(url.openStream());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte data[] = new byte[1024];
long total = 0;
try {
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
bar.setProgress(Integer.parseInt(progress[0]));
System.out.println(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String unused) {
}
int tryGetFileSize(URL url) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
return conn.getContentLength();
} catch (IOException e) {
return -1;
} finally {
conn.disconnect();
}
}
}
}
Related
I have an online music player in which I dedicated a button in order to download the file. There's a "progressDialog" which works fine and shows progress of downloading file and it seems that it's really downloading my file. But after completion there's no folder nor file on my device.
I also added Write External Storage permission in my manifest.
Here's my download class:
public class DownloadTask extends AsyncTask<String, Integer, String> {
#SuppressLint("StaticFieldLeak")
private Context context;
public static ProgressDialog progressBar;
public DownloadTask(Context context) {
this.context = context;
progressBar = new ProgressDialog(context);
progressBar.setMessage("Downloading...");
progressBar.setIndeterminate(true);
progressBar.setCancelable(true);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.show();
}
#Override
protected String doInBackground(String... strings) {
InputStream inputStream = null;
OutputStream outputStream = null;
HttpURLConnection connection = null;
try {
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
inputStream = connection.getInputStream();
fileCache();
outputStream = new FileOutputStream(context.getFilesDir() + "listening"
+ strings[1] + ".mp3");
byte[] data = new byte[4096];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1) {
total += count;
if (fileLength > 0)
publishProgress((int) (total * 100 / fileLength));
outputStream.write(data, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
if (inputStream != null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setIndeterminate(false);
progressBar.setMax(100);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.dismiss();
if (s != null) {
Toast.makeText(context, "Error while Downloading", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Downloaded successfully", Toast.LENGTH_SHORT).show();
}
}
private void fileCache() {
File myDir = new File(context.getFilesDir(), "listening");
if (!myDir.exists()) {
myDir.mkdirs();
}
}
}
And here's my button's function:
DownloadTask downloadTask = new DownloadTask(context);
downloadTask.execute(extra.getString("link"), extra.getString("title"));
Someone please read my code its given below,
the process dialog is not showing up,
seems like a minor mistake :D
Thanks in advance.
public class InternalData extends Activity implements OnClickListener {
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String FILENAME = "internalString";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedprefs);
InitializeVars();
}
public void InitializeVars() {
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (EditText) findViewById(R.id.etSharedPrefs);
dataResults = (TextView) findViewById(R.id.tvSharedPrefs);
save.setOnClickListener(this);
load.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bSave:
String data = sharedData.getText().toString();
/*
* //Saving data via File File f = new File(FILENAME); try { fos =
* new FileOutputStream(f); fos.close(); } catch(IOException e) {
* e.printStackTrace(); }
*/
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.bLoad:
new loadSomeStuff().execute(FILENAME);
break;
}
}
public class loadSomeStuff extends AsyncTask<String, Integer, String> {
ProgressDialog dialog = new ProgressDialog(InternalData.this);
protected void onPreExecute(String f) {
// dialog = new ProgressDialog(InternalData.this)
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
// all this can be done without making this whole AsyncTask class,
// but it will exaust our activity user interface, / slow it down
String collected = null;
FileInputStream fis = null;
for (int i = 0; i < 20; i++) {
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dialog.dismiss();
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1) {
collected = new String(dataArray);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
return collected;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
dialog.incrementProgressBy(progress[0]);
}
protected void onPostExecute(String result) {
dataResults.setText(result);
}
}
}
Change your onPreExecute() you're using it wrong, you should this instead
#Override
protected void onPreExecute() {
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
My while statement I have set up is causing my code underneath it to not be executed.
When I use this code here:
while ((count = is.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
}
to update the progress dialog bar for the file download, my other code I need to have doesn't get executed.
I'm not sure why this is behaving the way it is, if someone could explain and help, that would be great.
Full code:
public class SetWallpaperAsync extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog pDialog;
String image_url;
URL mImageUrl;
String myFileUrl1;
Bitmap bmImg = null;
public SetWallpaperAsync(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMessage("Downloading Image...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
pDialog.setMax(100);
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
InputStream is = null;
int count;
try {
mImageUrl = new URL(args[0]);
// myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) mImageUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
int lenghtOfFile = conn.getContentLength();
byte data[] = new byte[1024];
long total = 0;
while ((count = is.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
}
//This code doesn't get executed when using the code above
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.RGB_565;
bmImg = BitmapFactory.decodeStream(is, null, options);
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
}
}
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
if (bmImg == null) {
Toast.makeText(context, "Image still loading...",
Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
else {
WallpaperManager wpm = WallpaperManager.getInstance(context);
try {
wpm.setBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pDialog.dismiss();
Toast.makeText(context, "Wallpaper Successfully Set!",
Toast.LENGTH_SHORT).show();
}
}
}
Your while loop consumes all input there is i.e. until -1 end-of-stream is reached.
When you try to decode a bitmap from the same stream here:
bmImg = BitmapFactory.decodeStream(is, null, options);
... there's nothing to decode.
Probably there is some exception in the loop:
while ((count = is.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
}
that is causing the rest of the code for not being executed.
Check in the catch statement if there is some exception or debug for the code flow to identify the actual problem.
you need to set the maximum progress to content length...
protected String doInBackground(String... args) {
..........
final int contentLength = conn.getContentLength();
runOnUiThread(new Runnable() {
#Override
public void run() {
pDialog.setMax(contentLength);
}
});
.........
}
I am trying to write an application that downloads files in the background. The code crashes when it tries to reenter doInBackground(). This happens when doing is set to false before returning. Code follows -
public class DownloadFile extends AsyncTask<String, Integer, String> {
private boolean doing;
private Activity activity;
private Intent intent;
private File beta;
private File alpha;
public DownloadFile(Activity act, Intent intent) {
this.activity = act;
this.intent = intent;
doing = false;
}
#Override
protected String doInBackground(String... sUrl) {
int fileCount = 0;
if (!download(sUrl[0] + "list.txt",
Environment.getExternalStorageDirectory() + "/alpha/list.txt")){
setDoing(false);
return "Download failed";//list.txt could not be downloaded. return error message.
}
fileCount++;
beta = new File(Environment.getExternalStorageDirectory() + "/beta/");
File betalist = new File(beta + "/list.txt");
alpha = new File(Environment.getExternalStorageDirectory() + "/alpha/");
File alphalist = new File(alpha + "/list.txt");
//verify that the file is changed.
if (alphalist.lastModified() == betalist.lastModified()// these two are
// never equal.
|| alphalist.length() == betalist.length()) { // better to check
// the length of
// the files.
setDoing(false);
return "Nothing to download.";
}
try {
FileReader inAlpha = new FileReader(alphalist);
BufferedReader br = new BufferedReader(inAlpha);
String s;
// read the name of each file in a loop
while ((s = br.readLine()) != null) {
// if(fileExistsInBeta(s)){
// copyFromBetaToAlpha(s);
// continue;
// }
// download the file.
//Url will truncate the trailing / so keep if statement as is.
if (!download(sUrl[0] + s,
Environment.getExternalStorageDirectory() + "/alpha/"
+ s)){
setDoing(false);
return "Failed at " + s;// the given file could not be downloaded. return error.
}
fileCount++;
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("Pankaj", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Pankaj", e.getMessage());
} catch (Exception e) {
Log.e("Pankaj", e.getMessage());
}
Log.d("Pankaj", "Download Done");
activity.overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.finish();
Log.d("Pankaj", "MainActivity Killed");
// rename alpha to beta
deleteSubFolders(beta.toString());
beta.delete();
alpha.renameTo(beta);
if (!alpha.exists()) {
alpha.mkdir();
}
File upper = new File(alpha + "/upper/");
if (!upper.exists())
upper.mkdirs();
File lower = new File(alpha + "/lower/");
if (!lower.exists())
lower.mkdirs();
// ConfLoader.getInstance().reload();//to refresh the settings
// restart the activity
activity.overridePendingTransition(0, 0);
activity.startActivity(intent);
Log.d("Pankaj", "MainActivity restarted");
// now reset done status so we can start again.
setDoing(false);
return "Download finished.";// return the status for onPostExecute.
}
private void copyFromBetaToAlpha(String fileName) {
File beta=new File(Environment.getExternalStorageDirectory()+"/beta/"+fileName);
File alpha=new File(Environment.getExternalStorageDirectory()+"/alpha/"+fileName);
try {
FileInputStream fis=new FileInputStream(beta);
FileOutputStream fos=new FileOutputStream(alpha);
byte[] buf=new byte[1024];
int len;
while((len=fis.read(buf))>0){
fos.write(buf, 0, len);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
public boolean download(String url, String file) {
boolean successful = true;
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
conn.connect();
int filelen = conn.getContentLength();
File f = new File(file);
// skip download if lengths are same
// because the file has been downed fully.
if (f.exists() && filelen == f.length()) {
return successful;
}
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(f);
while ((length = dis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
buffer = null;
dis.close();
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
successful = false;
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
successful = false;
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
successful = false;
}
return successful;
}
private void deleteSubFolders(String uri) {
File currentFolder = new File(uri);
File files[] = currentFolder.listFiles();
if (files == null) {
return;
}
for (File f : files) {
if (f.isDirectory()) {
deleteSubFolders(f.toString());
}
// no else, or you'll never get rid of this folder!
f.delete();
}
}
public static int getFilesCount(File file) {
File[] files = file.listFiles();
int count = 0;
for (File f : files)
if (f.isDirectory())
count += getFilesCount(f);
else
count++;
return count;
}
public boolean isDoing() {
return doing;
}
/**
* #param doing
*/
public void setDoing(boolean doing) {
this.doing = doing;
}
private boolean fileExistsInBeta(final String fileName){
boolean exists=false;
File beta=new File(Environment.getExternalStorageDirectory()+"/beta/"+fileName);
if(beta.exists()){
String[] ext=beta.getName().split(".");
String extName=ext[ext.length-1];
exists=(extName!="txt" && extName!="tmr" && extName!="conf");
}
return exists;
}
in the main activity -
public void run() {
if (!downloadFile.isDoing()) {
downloadFile.execute(ConfLoader.getInstance().getListUrl());
downloadFile.setDoing(true);
}
// change the delay so that it covers the time for download and
// doesn't overlap causing multiple downloads jamming the bandwidth.
h.postDelayed(this, 1000);//check after 60 sec.
}
in the onCreate() -
downloadFile = new DownloadFile(this, getIntent());
h = new Handler();
h.postDelayed(this, 1000);
Any help is appreciated. Thanks in advance.
EDIT:
The logcat error is Cannot execute task the task is already running.
Cannot execute task: Task has already been executed(A task can only be executed once).
EDIT:
Is it possible that the error is because I am trying to execute the asynchtask again in run(). Perhaps AsynchTask does not allow re-entry.
Try using this
1. First create a dialogue
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
The download async task
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
File root = android.os.Environment.getExternalStorageDirectory();
//
File dir = new File (root.getAbsolutePath()+"/Downl");
if(dir.exists()==false) {
dir.mkdirs();
}
File file = new File(dir, url.substring(url.lastIndexOf("/")+1)); //name of file
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
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) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Toast.makeText(DisplayActivity.this,"Successfully downloaded in phone memory.", Toast.LENGTH_SHORT).show();
}
}
Call the async new DownloadFileAsync().execute(url); //pass ur url
I am making an application in which I need to download a file from server and save it to sd card of android device.
Apart of this there is a feature for the user to pause and resume the file.
The problem I am facing is that I am able to download file to sdcard but when try to pause and resume it, it gets starts from the beginning.......
Here is the source ......
public class DownloadWithProgressActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn, pauseButton, resumeButton;
private ProgressBar bar;
URLConnection conexion;
OutputStream output;
static int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button) findViewById(R.id.startBtn);
pauseButton = (Button) findViewById(R.id.button1);
resumeButton = (Button) findViewById(R.id.button2);
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setVisibility(ProgressBar.INVISIBLE);
bar.setId(0);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
resumeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// not getting what to write here
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String doInBackground(String... aurl) {
int downloaded = 0;
File file = new File("/sdcard/some_photo_from_gdansk_poland.jpg");
URL url = null;
try {
url = new URL(aurl[0]);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conexion = url.openConnection();
if (file.exists()) {
downloaded = (int) file.length();
conexion.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
else {
conexion.setRequestProperty("Range", "bytes=" + downloaded
+ "-");
}
} catch (Exception exception1) {
}
conexion.setDoInput(true);
conexion.setDoOutput(true);
System.out.println(tryGetFileSize(url));
conexion.setRequestProperty("Range", "bytes=" + count + "-");
try {
conexion.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = null;
try {
input = new BufferedInputStream(url.openStream());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte data[] = new byte[1024];
long total = 0;
try {
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
bar.setProgress(Integer.parseInt(progress[0]));
System.out.println(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String unused) {
}
int tryGetFileSize(URL url) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
return conn.getContentLength();
} catch (IOException e) {
return -1;
} finally {
conn.disconnect();
}
}
}
}
Please help.......
Thanks
Nikhil
connection.setRequestProperty("Range", "bytes=" + ***downloaded*** + "-");
Make "downloaded" as global variable, because download start from this position.
when you press on restart button, check value of this downloaded variable,must not zero all time.
This line return a wrong file size, I used the same code to open a Zip file on the net :
int lenghtOfFile = conexion.getContentLength();
How can I pause download other than by closing the output?
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
resumeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// not getting what to write here
}
});