In my app I'm using executor service to download a file from url. Now I want to add a horizontal progress bar to show the download progress. but I face errors. how can I add a progress bar in this code, without using async task?
private class ExecutorServiceDownload implements Runnable {
private String url;
public ExecutorServiceDownload(String url) {
this.url = url;
}
#Override
public void run() {
dlFile(url);
}
private String dlFile(String surl) {
try {
// I added progressbar here and it didn't download anything
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
URL url = new URL(surl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
input = connection.getInputStream();
String title = URLUtil.guessFileName(String.valueOf(url), null, null);
output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/test_files" + "/" + title);
int contentLength = connection.getContentLength();
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
}
return null;
}
}
Use this code for download with executor service:
in onCreate :
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreat`enter code here`e(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressbar);
downloading();
Downloading file with executor service:
private void downloading() {
progressBar.setVisibility(View.VISIBLE);
ExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Handler handler = new Handler(Looper.getMainLooper());
executor.execute(new Runnable() {
int count;
#Override
public void run() {
//Background work here
try {
// put your url.this is sample url.
URL url = new URL("http://techslides.com/demos/sample-videos/small.mp4");
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = conection.getInputStream();
//catalogfile is your destenition folder
OutputStream output = new FileOutputStream(catalogfile + "video.mp4");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress(Integer.valueOf("" + (int) ((total * 100) / lenghtOfFile)));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
handler.post(new Runnable() {
#Override
public void run() {
//UI Thread work here
progressBar.setVisibility(View.GONE);
}
});
} catch (Exception e) {
}
}
});
}
update progressbar
private void publishProgress(Integer... progress) {
progressBar.setProgress(progress[0]);
}
and horizontal progress bar use :
<ProgressBar
android:max="100"
style="?android:attr/progressBarStyleHorizontal"
android:visibility="invisible"
android:id="#+id/progressbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
Related
Below is my AsyncTask to download a PDF file from CloudBoost database. The code works and downloads the file; however, what does not work is the progress bar update because the file length returned is -1. Can someone give me a tip on how I can deal with this.
By the way loading.setProgress(progress[0]); line in the the progress update method is being initialized at the top of the class that this AsyncTask class is nested in.
class DownloadPdfFromInternet extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
int count;
try {
URL url = new URL(strings[0]);
URLConnection connection = url.openConnection();
connection.connect();
// get length of file
int lengthOfFile = connection.getContentLength();
Log.d("dozer74", "LengthOf File: " + lengthOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + pubName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lengthOfFile));
// write data to file
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
loading.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String url) {
loading.dismiss();
openPdfFile();
}
}
I create a file download from web
This code works but after i go to home page , how can access to thread and this listener ?
filedownloader.java
public class FileDownloader {
public static void download(final String downloadPath, final String filepath, final OnProgressDownloadListener listener) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//connection.setDoOutput(true);
connection.connect();
int fileSize = connection.getContentLength();
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
FileOutputStream outputStream = new FileOutputStream(filepath);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
int downloadedSize = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
downloadedSize += len;
final float downloadPercent = 100.0f * (float) downloadedSize / fileSize;
if (listener != null) {
G.HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onProgressDownload((int) downloadPercent);
}
});
}
}
outputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
onprogressdownloadlistener.java
public interface OnProgressDownloadListener {
public void onProgressDownload(int percent);
}
mainactivity.java
OnProgressDownloadListener listener = new OnProgressDownloadListener() {
#Override
public void onProgressDownload(final int percent) {
Log.i(percent + "%");
}
};
FileDownloader.download(dlFile, G.DIR_APP + "/" + fileName, listener);
Percent return size of download
After start download and close page and go to new page , i want to go back to download page. how to access this thread and the listener ?
Thanks
-Hey you can check if percent in main activity's listener object gets "100%" value then you can get you desired output.
protected void doDownload(final String urlLink, final String fileName) {
Thread dx = new Thread() {
public void run() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Content2/");
if(dir.exists()==false) {
dir.mkdirs();
}
//Save the path as a string value
try
{
URL url = new URL(urlLink);
Log.i("FILE_NAME", "File name is "+imageFile);
Log.i("FILE_URLLINK", "File URL is "+url);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(dir+"/"+imageFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
Log.i("ERROR ON DOWNLOADING FILES", "ERROR IS" +e);
}
}
};
dx.start();
}
through this, I cannot download the file from the server.
How to solve this problem?
First of all you should use Async-Task.
Here is how you can do this
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
am using sound cloud search api. when i hit the search url it give me search results. every audio has stream url but not download url because it depends on setting of the uploader. Every none downloadable file also has download count more than 1. for example, when you'll hit this url
http://api.soundcloud.com/tracks.json?client_id=4346c8125f4f5c40ad666bacd8e96498&q=tere%20bin&limit=1
It'll give the search result like that
[{"kind":"track","id":63225776,"created_at":"2012/10/13 01:52:38 +0000","user_id":26029726,"duration":206177,"commentable":true,"state":"finished","original_content_size":3298521,"last_modified":"2014/10/01 18:56:25 +0000","sharing":"public","tag_list":"","permalink":"tere-bin-uzair-jaswal-official","streamable":true,"embeddable_by":"all","downloadable":false,"purchase_url":null,"label_id":null,"purchase_title":null,"genre":"Musical","title":"Tere Bin - Uzair Jaswal [Official Music Audio]","description":"","label_name":"","release":"","track_type":"original","key_signature":"","isrc":"","video_url":null,"bpm":null,"release_year":null,"release_month":null,"release_day":null,"original_format":"mp3","license":"all-rights-reserved","uri":"https://api.soundcloud.com/tracks/63225776","user":{"id":26029726,"kind":"user","permalink":"uzair-jaswal-1","username":"Uzair Jaswal Music","last_modified":"2014/10/19 13:06:28 +0000","uri":"https://api.soundcloud.com/users/26029726","permalink_url":"http://soundcloud.com/uzair-jaswal-1","avatar_url":"https://i1.sndcdn.com/avatars-000110064166-2ts508-large.jpg"},"permalink_url":"http://soundcloud.com/uzair-jaswal-1/tere-bin-uzair-jaswal-official","artwork_url":"https://i1.sndcdn.com/artworks-000032079002-kup6vc-large.jpg","waveform_url":"https://w1.sndcdn.com/9bwAsZfGrxwN_m.png","stream_url":"https://api.soundcloud.com/tracks/63225776/stream","playback_count":359588,"download_count":100,"favoritings_count":7557,"comment_count":491,"attachments_uri":"https://api.soundcloud.com/tracks/63225776/attachments","policy":"ALLOW"}]
this is for only one audio and that audio is not downloadable but it has download count of 100. how is this possible ?
can anybody tell me how i can download that audio which is not downloadable?
any help would be much appreciated. Thanks :)
I fix it myself, i was using android and the stream url is also a download url. the stream url is also download url for downloading but it won't affect on download count. you can try like that
String file_url = "https://api.soundcloud.com/tracks/93216523/stream?client_id=4346c8125f4f5c40ad666bacd8e96498";
pass this url to asyntack and manage you download there, you can pass it like that
new DownloadFileFromURL().execute(file_url);
here is DownloadFileFromUR class using asyntask
class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
URL u = null;
InputStream is = null;
try {
u = new URL(f_url[0]);
is = u.openStream();
HttpURLConnection huc = (HttpURLConnection)u.openConnection();//to know the size of video
int size = huc.getContentLength();
if(huc != null){
String fileName = "FILE2.mp3";
String storagePath = Environment.getExternalStorageDirectory().toString();
File f = new File(storagePath,fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[1024];
long total = 0;
int len1 = 0;
if(is != null){
while ((len1 = is.read(buffer)) > 0) {
total+=len1;
publishProgress((int)((total*100)/size));
fos.write(buffer,0, len1);
}
}
if(fos != null){
fos.close();
}
}
}catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(is != null){
is.close();
}
}catch (IOException ioe) {
// just going to ignore this one
}
}
return "";
}
#Override
protected void onPostExecute(String file_url) {
}
}
String file_url = "https://api.soundcloud.com/tracks/93216523/stream?client_id=4346c8125f4f5c40ad666bacd8e96498";
DownLoad Class:
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count;
try {
URL url = new URL(file_url);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(getOutputMediaFile());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
I'm downloading a file from a server and for some reason i can't determine, the downloaded file size doesn't match the original file size. Here's my code.
private class dl extends AsyncTask<String,Integer,Void>
{
int size;
#Override
protected Void doInBackground(String... arg0) {
// TODO Auto-generated method stub
try{
URL myFileUrl = new URL("http://10.0.2.2:8080/testdlapps/chrome-beta.zip");
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.connect();
InputStream is = conn.getInputStream();
size = conn.getContentLength();
Log.v("INFO---------------------", "size is " +size);
FileOutputStream fout1 = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+"xyz.zip");
BufferedOutputStream bos = new BufferedOutputStream(fout1);
byte[] b = new byte[1024]; int i=0, count=0;
while((count = is.read(b)) != -1)
{
bos.write(b,0,count);
i+=count;
publishProgress(i);
Log.v("INFO----------------------------",""+count);
}
fout1.close();
}catch(Exception e){
Log.v("INFO--------------------------","Error!!");
Log.v("INFO--------------------------",e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
tv.setText("downloaded " + progress[0] + "/" + size ); //tv is a TextView
}
}
When i run the app, after the download completes, count and size are the same but the actual file size i.e /mnt/sdcard/xyz.zip is always less than size. Any ideas what going wrong?
override onPostExecute and check if actually it finishes, perhaps here a code to download with resume support,
pay attention because if you press back the download may still run:
if (isCancelled())
return false;
in the loop is needed because the close() on the socket will hang on exit without you noticeing it
here is the code:
class DownloaderTask extends AsyncTask<String, Integer, Boolean>
{
private ProgressDialog mProgress;
private Context mContext;
private Long mFileSize;
private Long mDownloaded;
private String mDestFile;
public DownloaderTask(Context context, String path)
{
mContext = context;
mFileSize = 1L;
mDownloaded = 0L;
mDestFile = path;
}
#Override
protected void onPreExecute()
{
mProgress = new ProgressDialog(mContext);
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setMessage("Downloading...");
mProgress.setCancelable(true);
mProgress.setCanceledOnTouchOutside(false);
mProgress.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
DownloaderTask.this.cancel(true);
}
});
mProgress.show();
}
#Override
protected void onProgressUpdate(Integer... percent)
{
mProgress.setProgress(percent[0]);
}
#Override
protected Boolean doInBackground(String... urls)
{
FileOutputStream fos = null;
BufferedInputStream in = null;
BufferedOutputStream out = null;
AndroidHttpClient mClient = AndroidHttpClient.newInstance("AndroidDownloader");
try
{
HttpResponse response = null;
HttpHead head = new HttpHead(urls[0]);
response = mClient.execute(head);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
return false;
Boolean resumable = response.getLastHeader("Accept-Ranges").getValue().equals("bytes");
File file = new File(mDestFile);
mFileSize = (long) Integer.parseInt(response.getLastHeader("Content-Length").getValue());
mDownloaded = file.length();
if (!resumable || (mDownloaded >= mFileSize))
{
Log.e(TAG, "Invalid size / Non resumable - removing file");
file.delete();
mDownloaded = 0L;
}
HttpGet get = new HttpGet(urls[0]);
if (mDownloaded > 0)
{
Log.i(TAG, "Resume download from " + mDownloaded);
get.setHeader("Range", "bytes=" + mDownloaded + "-");
}
response = mClient.execute(get);
if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) && (response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT))
return false;
if (mDownloaded > 0)
publishProgress((int) ((mDownloaded / mFileSize) * 100));
in = new BufferedInputStream(response.getEntity().getContent());
fos = new FileOutputStream(file, true);
out = new BufferedOutputStream(fos);
byte[] buffer = new byte[8192];
int n = 0;
while ((n = in.read(buffer, 0, buffer.length)) != -1)
{
if (isCancelled())
return false;
out.write(buffer, 0, n);
mDownloaded += n;
publishProgress((int) ((mDownloaded / (float) mFileSize) * 100));
}
} catch (Exception e)
{
e.printStackTrace();
return false;
} finally
{
try
{
mClient.close();
if (in != null)
in.close();
if (out != null)
out.close();
if (fos != null)
fos.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return true;
}
#Override
protected void onCancelled()
{
finish();
}
#Override
protected void onPostExecute(Boolean result)
{
if (mProgress.isShowing())
mProgress.dismiss();
if (result)
// done
else
// error
}
}
If it is a chunked response, the content-length in the header will be a guess at best.