Download a file with no extension from a server - android

I'm try to download a mp3 file from following URL. I found lot of articles and examples regarding file download. Those examples are based on URLs that end with a file extension, e.g.:- yourdomain.com/filename.mp3 but I want to download a file from following url which typically does not end with file extension.
youtubeinmp3.com/download/get/?i=1gsE32jF0aVaY0smDVf%2BmwnIZPrMDnGmchHBu0Hovd3Hl4NYqjNdym4RqjDSAis7p1n5O%2BeXmdwFxK9ugErLWQ%3D%3D
**Please note that I use the above url as-is without using Stackoverflow url formatting method to easily understand the question.
** I have tried the #Arsal Imam's solution as follows still not working
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
File cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Folder Name");
if(!cacheDir.exists())
cacheDir.mkdirs();
File f=new File(cacheDir,"ddedddddd.mp3");
saveDir=f.getPath();
new DownloadFileFromURL().execute(fileURL);
}
});
and the async task code is as follows
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
try{
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveDir);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}
}

Although Volley library is not recommended for large download or streaming operations, however, I'd like to share my following working sample code.
Let's assume we download only MP3 files so I hard-code the extension. And of course, we should check more carefully to avoid exceptions (NullPointer...) such as checking whether headers contain "Content-Disposition" key or not...
Hope this helps!
Volley Custom class:
public class BaseVolleyRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
public BaseVolleyRequest(String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(0, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
Then in your Activity:
public class BinaryVolleyActivity extends AppCompatActivity {
private final Context mContext = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binary_volley);
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
String url = "http://www.youtubeinmp3.com/download/get/?i=3sI2yV5mJ0kQ8CnddqmANZqK8a%2BgVQJ%2Fmg3xwhHTUsJKuusOCZUzebuWW%2BJSFs0oz8VTs6ES3gjohKQMogixlQ%3D%3D";
BaseVolleyRequest volleyRequest = new BaseVolleyRequest(url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
Map<String, String> headers = response.headers;
String contentDisposition = headers.get("Content-Disposition");
// String contentType = headers.get("Content-Type");
String[] temp = contentDisposition.split("filename=");
String fileName = temp[1].replace("\"", "") + ".mp3";
InputStream inputStream = new ByteArrayInputStream(response.data);
createLocalFile(inputStream, fileName);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
volleyRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 10, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(volleyRequest);
}
private String createLocalFile(InputStream inputStream, String fileName) {
try {
String folderName = "MP3VOLLEY";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, folderName);
folder.mkdir();
File file = new File(folder, fileName);
file.createNewFile();
FileOutputStream f = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
f.write(buffer, 0, length);
}
//f.flush();
f.close();
return file.getPath();
} catch (IOException e) {
return e.getMessage();
}
}
}
Here the result screenshot:
NOTE:
As I commented below, because the direct download Url changes regularly, you should check the new url with some tools such as Postman for Chrome, if it responses binary instead of a web page (expired url), then the Url is valid and my code works for that Url.
Refer to the two following screenshots:
Expired url:
Un-expired url:
UPDATE BASIC LOGIC FOR GETTING DIRECT DOWNLOAD LINK FROM THAT SITE'S DOCUMENTATION:
According to Create Your Own YouTube To MP3 Downloader For Free
You can take a look at
JSON Example
You can also receive the data in JSON by setting the "format"
parameter to "JSON".
http://YouTubeInMP3.com/fetch/?format=JSON&video=http://www.youtube.com/watch?v=i62Zjga8JOM
Firstly, you create a JsonObjectRequest getting response from the above file link. Then, inside onResponse of this JsonObjectRequest you will get the direct download link, like this directUrl = response.getString("link"); and use BaseVolleyRequest volleyRequest
I have just told the logic for getting direct url, IMO, you should implement it yourself. Goodluck!

Use below code it works fine for encrypted URLs
public class HttpDownloadUtility {
private static final int BUFFER_SIZE = 4096;
/**
* Downloads a file from a URL
* #param fileURL HTTP URL of the file to be downloaded
* #param saveDir path of the directory to save the file
* #throws IOException
*/
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}

The url returns a 302 redirect to the actual .mp3. The browser does the redirect in the background for you, but in your app you need to do it yourself. Here is an example on how to do that with HttpUrlConnection http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/

If you know the type of file in advance then you can download your file from url which don't have extension.
DownloadService .java
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
private Context context;
private PowerManager.WakeLock mWakeLock;
ProgressDialog mProgressDialog;
String filename;
File mypath;
String urlToDownload;
BroadcastReceiver broadcaster;
Intent intent1;
static final public String BROADCAST_ACTION = "com.example.app.activity.test.broadcast";
public DownloadService() {
super("DownloadService");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
intent1 = new Intent(BROADCAST_ACTION);
}
#Override
protected void onHandleIntent(Intent intent) {
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
intent1 = new Intent(BROADCAST_ACTION);
urlToDownload = intent.getStringExtra("url");
filename= intent.getStringExtra("filename");
BufferedWriter out;
try {
File path=new File("/sdcard/","folder name");
path.mkdir();
mypath=new File(path,filename);
Log.e("mypath",""+mypath);
if (!mypath.exists()) {
out= new BufferedWriter(new FileWriter(mypath));
//ut = new OutputStreamWriter(context.openFileOutput( mypath.getAbsolutePath() ,Context.MODE_PRIVATE));
out.write("test");
out.close();
}
}catch(Exception e){
e.printStackTrace();
}
URL url = new URL(urlToDownload);
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(connection.getInputStream());
OutputStream output = new FileOutputStream(mypath);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
//Log.e("mypath",""+mypath);
resultData.putString("mypath", ""+mypath);
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
resultData.putString("mypath", ""+mypath);
receiver.send(UPDATE_PROGRESS, resultData);
intent1.putExtra("progressbar", 100);
sendBroadcast(intent1);
}
}
DownloadReceiver.java
public class DownloadReceiver extends ResultReceiver{
private Context context;
private PowerManager.WakeLock mWakeLock;
ProgressDialog mProgressDialog;
String filename;
String mypath;
public DownloadReceiver(Handler handler ,String filename ,Context context) {
super(handler);
this.context = context;
this.filename = filename;
mProgressDialog = new ProgressDialog(context);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
mypath = resultData.getString("mypath");
mProgressDialog.setProgress(progress);
//Log.e("progress","progress");
mProgressDialog.setMessage("App name");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
if (progress == 100) {
mProgressDialog.dismiss();
Log.e("download","download");
}
}
}
}
Now start service in your mainactivity by below code :
Intent miIntent = new Intent(mContext, DownloadService.class);
miIntent.putExtra("url", url);
miIntent.putExtra("filename", id+".mp3");
miIntent.putExtra("receiver", new DownloadReceiver(new Handler() , id,mContext));
startService(miIntent);

Related

How to cancel file downloading from a dialog

When user download a file, I show user a dialog that contain a cancel button.
My problem is when user press the cancel button on dialog file, the downloading process won't be cancel.
I want when user press cancel button either file download complete or not, I the must be delete.
Please explain anyone how I can do this.
Code:
public class DownloadTask {
private static final String TAG = "Download Task";
private Context context;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
public DownloadTask(Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = downloadUrl;
downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf( '/' ),downloadUrl.length());
Log.e(TAG, downloadFileName);
//Start Downloading Task
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Integer, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(bookejtemaeat.this);
progressDialog.setMessage("يتم تحميل الملف مرة واحدة يرجى الانتظار ......");
progressDialog.setIndeterminate(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setCanceledOnTouchOutside(false) ;
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DownloadingTask.this.cancel(true);
dialog.dismiss();
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URL
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
final int fileLength = c.getContentLength();
Log.e(TAG, "fileLength " + fileLength);
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = getApplicationContext().getDir(
"NKDROID FILES",Context.MODE_PRIVATE);
} else
Toast.makeText(context, "Tidak ada SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
long total = 0;
while ((len1 = is.read(buffer)) != -1) {
total += len1;
final long total_tmp = total;
Log.e(TAG, "progressDialog " + (total*100/fileLength));
publishProgress((int) (total * 100 / fileLength));
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.setProgress((int) (total_tmp*100/fileLength));
}
});
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
}
Just add a boolean value in your class that will let you control while loop. like
while (continueDownload&& (len1 = is.read(buffer)) != -1) {
and make this work like
yourDwnloadTask.setContinueDownload(false);
and handle your output file
if (!continueDownload && outputFile.exists()) {
try {
outputFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
If you ask me full code.
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadTask {
private static final String TAG = "Download Task";
private Context context;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
private boolean continueDownload = true;
public void setContinueDownload(boolean continueDownload) {
this.continueDownload = continueDownload;
}
public DownloadTask(Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = downloadUrl;
downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'), downloadUrl.length());
continueDownload = true;
Log.e(TAG, downloadFileName);
//Start Downloading Task
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Integer, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(bookejtemaeat.this);
progressDialog.setMessage("يتم تحميل الملف مرة واحدة يرجى الانتظار ......");
progressDialog.setIndeterminate(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DownloadingTask.this.cancel(true);
dialog.dismiss();
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URL
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
final int fileLength = c.getContentLength();
Log.e(TAG, "fileLength " + fileLength);
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = getApplicationContext().getDir(
"NKDROID FILES", Context.MODE_PRIVATE);
} else
Toast.makeText(context, "Tidak ada SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
long total = 0;
while (continueDownload && (len1 = is.read(buffer)) != -1) {
total += len1;
final long total_tmp = total;
Log.e(TAG, "progressDialog " + (total * 100 / fileLength));
publishProgress((int) (total * 100 / fileLength));
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.setProgress((int) (total_tmp * 100 / fileLength));
}
});
fos.write(buffer, 0, len1);//Write new file
}
if (!continueDownload && outputFile.exists()) {
try {
outputFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
}

Download HTML file from URL using Retrofit

I am getting a URL in response. I want to download the html of that URL so that user can see it offline also. Its a recyclerView in which each items contain a URL. So when user clicks on the URL of one item it should save it in external disk.
Below is the code:
NewsAdapter:
case R.id.save:
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.nytimes.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Log.i("Retrofit build", "initiated");
ApiInterface retrofitInterface = retrofit.create(ApiInterface.class);
final Call< ResponseBody > call = retrofitInterface.downloadFileWithDynamicUrlSync("2017/09/13/us/nursing-home-deaths-florida.html");
Log.i("Retrofit req execute", "initiated");
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
boolean writtenToDisk = false;
try {
writtenToDisk = writeResponseBodyToDisk(call.execute().body());
} catch (IOException e) {
e.printStackTrace();
}
;
Log.d("success", "file download was a success? " + writtenToDisk);
return null;
}
}.execute();
break;
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.DIRECTORY_DOWNLOADS + File.separator + "Future Studio Icon.png");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.d("filedownload", "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
ApiInterface:
// option 2: using a dynamic URL
#Streaming
#GET
Call<ResponseBody> downloadFileWithDynamicUrlSync(#Url String fileUrl);
I am also getting the error:
Failed to invoke public com.squareup.okhttp.ResponseBody() with no args
Can someone tell me how to implement it correctly.
Use URL with domain name to download file.Remove streaming annotation don't need that.
You are not receiving file body as you are not using complete URL.
Create an interface like this
#GET
Call<ResponseBody> downloadFile(#Url String url);
Then use this code :
public void onResponse(Call<ResponseBody> call, Response<ResponseBody>
response)
{
if (response.isSuccessful()) {
String filePath = Utils.downloadFile(response.body(),"filename");
}
}
public String downloadFile(ResponseBody body, String fileName) {
String filePath = null;
try {
int count;
byte data[] = new byte[1024 * 4];
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
File storageDir = new File(Environment.getExternalStorageDirectory(), "AppName");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
File outputFile = new File(storageDir, fileName);
OutputStream output = new FileOutputStream(outputFile);
while ((count = bis.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
bis.close();
filePath = outputFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}

How to show upload Progress for multiple uploads separately - Android

How should can I show progress bar for each file I upload in android using an upload button, something like this:
I have tried doing so using services and notification but I would like to show progress in the UI itself.
Any Code Sample will help.
I am using the following Class for multipart upload:
public class MultipartUtility
{
FileUploadListener listener;
private static final int BUFFER_SIZE = 1024;
private static final int TIME_OUT = 3 * 60 * 1000;
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public int statusCode;
public String mURL;
public interface FileUploadListener {
void onUpdateProgress(int percentage, long kb);
boolean isCanceled();
}
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* #param requestURL
* #param charset
* #throws IOException
*/
public MultipartUtility(Context context, String requestURL, String charset, FileUploadListener listener)
throws IOException {
this.charset = charset;
this.listener = listener;
mURL = requestURL;
// creates a unique boundary based on time stamp
boundary = "" + System.currentTimeMillis() + "";
URL url = new URL(requestURL);
httpConn = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
httpConn = https;
} else {
httpConn = (HttpURLConnection) url.openConnection();
}
// httpConn.setConnectTimeout(TIME_OUT);
//httpConn.setReadTimeout(TIME_OUT);
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setChunkedStreamingMode(BUFFER_SIZE);
httpConn.setRequestMethod("POST");
Storage storage = new Storage(context);
httpConn.setRequestProperty("x-auth", storage.readString("user_token"));
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("Connection", "Keep-Alive");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adds a form field to the request
*
* #param name field name
* #param value field value
*/
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
/**
* Adds a upload file section to the request
*
* #param fieldName name attribute in <input type="file" name="..." />
* #param uploadFile a File to be uploaded
* #throws IOException
*/
private long lastProgressUpdateTime = 0;
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
outputStream.flush();
byte[] buffer = new byte[BUFFER_SIZE];
try {
final FileInputStream inputStream = new FileInputStream(uploadFile);
long totalRead = 0;
long totalSize = uploadFile.length();
int read;
while ((read = inputStream.read(buffer)) > 0) {
totalRead += read;
int percentage = (int) ((totalRead / (float) totalSize) * 100);
outputStream.write(buffer, 0, read);
long now = System.currentTimeMillis();
if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < now - 100) {
lastProgressUpdateTime = now;
Log.e("", totalRead + " " + " " + percentage);
if (listener != null)
this.listener.onUpdateProgress(percentage, totalRead);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.flush();
}
writer.append(LINE_FEED);
writer.flush();
}
/**
* Adds a header field to the request.
*
* #param name - name of the header field
* #param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
*
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
public String Execute() throws IOException {
String responses = "";
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
StringBuilder sb = new StringBuilder();
try {
// checks server's status code first
statusCode = httpConn.getResponseCode();
//responses = ;
sb.append("" + Helpers.convertStreamToString(httpConn.getInputStream()) + "\n");
if (statusCode == HttpURLConnection.HTTP_OK) {
httpConn.disconnect();
}
responses = sb.toString();
return responses;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
sb = new StringBuilder();
sb.append("" + Helpers.convertStreamToString(httpConn.getErrorStream()) + "\n");
responses = sb.toString();
}
return responses;
}
}
Create a singleton design for this and for every downloading file create an entry in HashMap entry with key value. For example for file1 there should be a key and value should be its updated progress. And update that entry according to file upload progress(when the call back of on progress update receive) against the key. And also update the progress bar from that hash map according to key.Because your hash map will always have updated values. Hope that helps.
In one of my project I implemented the same thing. I am sharing that now
Create download service
public class DownloadService extends IntentService {
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String rhymeName = intent.getStringExtra(Constants.RHYME_NAME);
String URL = intent.getStringExtra(Constants.URL);
downloadRhyme(rhymeName, URL);
}
private void sendMyBroadCast(long currentProgress, long totalVideoSize, String rhymeName) {
Intent intentUpdate = new Intent();
intentUpdate.setAction(Constants.ACTION_MYUPDATE);
intentUpdate.addCategory(Intent.CATEGORY_DEFAULT);
intentUpdate.putExtra(Constants.UPDATED_VALUES, currentProgress);
intentUpdate.putExtra(Constants.TOTAL_VIDEO_SIZE, totalVideoSize);
intentUpdate.putExtra(Constants.RHYME_NAME, rhymeName);
sendBroadcast(intentUpdate);
}
private void registerMyTaskCompletedListener(ITaskCompletedListener taskCompletedListener, boolean successful, String rhymeName) {
if (successful)
taskCompletedListener.taskCompleted(rhymeName);
else
taskCompletedListener.taskFailed(rhymeName);
}
private final void downloadRhyme(String rhymeName, String URL) {
boolean successful = false;
URL downloadURL = null;
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
File file = null;
try {
downloadURL = new URL(URL);
httpURLConnection = (HttpURLConnection) downloadURL.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK)
return;
inputStream = httpURLConnection.getInputStream();
file = AppUtility.getInternalDirectoryForRhymes(this, rhymeName);
fileOutputStream = new FileOutputStream(file);
int read = -1;
long totalRead =0 ;
int totalLength = httpURLConnection.getContentLength();
byte [] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
totalRead += read;
fileOutputStream.write(buffer, 0, read);
sendMyBroadCast(totalRead, totalLength, rhymeName);
}
successful = true;
UrduRhymesActivity.getInstance().unregisterMyReceiver();
callListener(successful, rhymeName);
} catch (Exception e) {
if (e instanceof SocketTimeoutException) {
ProgressReceiver.showSocketConnectionDialogue();
}
callListener(successful, rhymeName);
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void callListener(boolean successful, String rhymeName) {
ITaskCompletedListener taskCompletedListener = new ProgressReceiver();
registerMyTaskCompletedListener(taskCompletedListener, successful, rhymeName);
}
}
Below is the progress receiver
public class ProgressReceiver extends BroadcastReceiver implements ITaskCompletedListener {
#Override
public void onReceive(Context context, Intent intent) {
long currentProgress = intent.getLongExtra(Constants.UPDATED_VALUES, 0);
long totalSize = intent.getLongExtra(Constants.TOTAL_VIDEO_SIZE, 0);
String rhymeName = intent.getStringExtra(Constants.RHYME_NAME);
ProgressbarDetails progressbarDetails = ProgressbarDetails.getProgressDetail(rhymeName);
if (progressbarDetails != null) {
int updates = ((int) ((currentProgress / (float) totalSize) * 100));
progressbarDetails.prgProgressBar.setVisibility(View.VISIBLE);
progressbarDetails.prgProgressBar.setProgress(updates);
LogUtility.infoLog("current downloaded file size is " + currentProgress);
LogUtility.infoLog("total file size " + totalSize);
LogUtility.infoLog("After conversion " + updates);
}
}
#Override
public void taskCompleted(String rhymeName) {
runThread(rhymeName);
}
private void runThread(final String rhymeName) {
UrduRhymesActivity.getInstance().runOnUiThread(new Runnable() {
#Override
public void run() {
ProgressbarDetails progressbarDetails = ProgressbarDetails.getProgressDetail(rhymeName);
progressbarDetails.download_btn_settings.setBackgroundResource(R.mipmap.btn_play);
progressbarDetails.prgProgressBar.setVisibility(View.GONE);
ProgressbarDetails.deleteUpdateProgressDetail(rhymeName);
}
});
}
public static void showSocketConnectionDialogue() {
UrduRhymesActivity.getInstance().runOnUiThread(new Runnable() {
#Override
public void run() {
//[Case:When server is down]
AppUtility.showConnectionDialoge(UrduRhymesActivity.sUrduRhymesActivity);
}
});
}
#Override
public void taskFailed(String rhymeName) {
boolean deleteStatus = false;
if (rhymeName != null)
deleteStatus = AppUtility.deleteFileFromInternalDirectory(MyApplication.getAppContext(), rhymeName);
if (deleteStatus)
LogUtility.infoLog("file deleted Successfully");
else LogUtility.infoLog("File not deleted");
ProgressbarDetails.deleteUpdateProgressDetail(rhymeName);
}
}
Here is the main code that keeps track of downloading status.
public class ProgressbarDetails {
public ProgressBar prgProgressBar;
public int progress;
public LinearLayout download_btn_settings;
private static HashMap<String, ProgressbarDetails> progressMapper = null;
public static HashMap<String, ProgressbarDetails> getProgressMapper() {
if(progressMapper == null)
progressMapper = new HashMap<>();
return progressMapper;
}
public static ProgressbarDetails getProgressDetail(String rhymeName) {
Object obj = getProgressMapper().get(rhymeName);
ProgressbarDetails ProgressbarDetails = null;
if (obj != null)
ProgressbarDetails = (ProgressbarDetails) obj;
return ProgressbarDetails;
}
public static void addUpdateProgressDetail(String rhymeName, ProgressbarDetails prgBarDetail) {
progressMapper = getProgressMapper();
progressMapper.put(rhymeName, prgBarDetail);
}
public static void deleteUpdateProgressDetail(String rhymeName) {
progressMapper = getProgressMapper();
if(progressMapper.containsKey(rhymeName))
progressMapper.remove(rhymeName);
}
}
Hope that helps.
This is how I would do it:
Create a RecyclerView to hold each upload progress row
Upon starting a new upload - add new item (row) to the RecyclerView
You need to keep some kind of mapping between the RecyclerView row position and the upload task it represents (HashMap is a good option)
Listen to the upload progress of your task (I see you have a listener already implemented) and when an update arrives - query to HashMap from step 3 to check which RecyclerView row you need to update.
Update the RecyclerView row with the position from step 4.
Some resources to get you started:
Working with Recycler View
How to add new item to RecyclerView
How to update/refresh specific item in RecyclerView
Java HashMap class

How to download video from URL?

I am trying to download a video file from URL.
Below is my Code.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBack PB = new ProgressBack();
PB.execute("");
}
private class ProgressBack extends AsyncTask<String, String, String> {
ProgressDialog PD;
#Override
protected void onPreExecute() {
PD = ProgressDialog.show(MainActivity.this, null, "Please Wait ...", true);
PD.setCancelable(true);
}
#Override
protected String doInBackground(String... arg0) {
downloadFile("https://r8---sn-nhpax-ua8z.googlevideo.com/videoplayback?c=web&clen=17641691&cpn=Mf_hDzzzBYPH8N_J&cver=as3&dur=189.857&expire=1425270280&fexp=905657%2C907263%2C912333%2C926419%2C927622%2C931358%2C934947%2C936928%2C9406255%2C9406746%2C9406850%2C943917%2C945093%2C947225%2C947240%2C948124%2C951703%2C952302%2C952605%2C952612%2C952620%2C952901%2C955301%2C957201%2C959701&gcr=il&gir=yes&id=o-AM54E58Im9m8yqaerEsKkGXOx0IWge8YN4h6OhFkcDTe&initcwndbps=1488750&ip=84.228.53.86&ipbits=0&itag=135&keepalive=yes&key=yt5&lmt=1402678222642477&mime=video%2Fmp4&mm=31&ms=au&mt=1425248654&mv=m&pl=20&ratebypass=yes&requiressl=yes&signature=E8027BCB4C1EE76254FC008B0044655E58485D81.931863F3A7AD6C6B01262BCD723B37E5396D4317&source=youtube&sparams=clen%2Cdur%2Cgcr%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Ckeepalive%2Clmt%2Cmime%2Cmm%2Cms%2Cmv%2Cpl%2Crequiressl%2Csource%2Cupn%2Cexpire&sver=3&upn=moGJHdfD4Z8", "Sample.mp4");
return null;
}
protected void onPostExecute(Boolean result) {
PD.dismiss();
}
}
private void downloadFile(String fileURL, String fileName) {
try {
String rootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File rootFile = new File(rootDir);
rootFile.mkdir();
URL url = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(rootFile,
fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (IOException e) {
Log.d("Error....", e.toString());
}
}
}
But it is not downloading. and it is showing java.io.FileNotFoundException.
Is there any other way to download video file or anything wrong in my code.
Can someone please help me?
//Check if External Storage permission js allowed
if (!storageAllowed()) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(getActivity(), Constant.PERMISSIONS_STORAGE, Constant.REQUEST_EXTERNAL_STORAGE);
progressDialog.dismiss();
showToast("Kindly grant the request and try again");
}else {
String mBaseFolderPath = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "FolderName" + File.separator;
if (!new File(mBaseFolderPath).exists()) {
new File(mBaseFolderPath).mkdir();
}
if (downloadUrl == null || TextUtils.isEmpty(downloadUrl)) {
showToast("Download url not found!");
return;
}
Uri downloadUri = Uri.parse(url.trim());
if (downloadUri == null) {
showToast("Download url not found!");
return;
}
String mFilePath = "file://" + mBaseFolderPath + "/" + fname ;
DownloadManager.Request req = new DownloadManager.Request(downloadUri);
req.setDestinationUri(Uri.parse(mFilePath));
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
dm.enqueue(req);
progressDialog.dismiss();
loadInterstitialAd();
}
}
try out this:
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
You can use DownloadManger for downloading file in android from server.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(videoUrl))
.setTitle(file.getName())
.setDescription("Downloading")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationUri(Uri.fromFile(file))
.setAllowedOverMetered(true)
.setAllowedOverRoaming(true);
long downloadId = mDownloadManager.enqueue(request);

Download more than 500 mb size video or image file from server to sdcard in android?

i am trying to download images and videos from server to sdcard for offline play.
but problem is if image and video size is morethan 35 mb than video is not dowloaded and app is crash.
my image size is upto 50mb and video size is 50 to 500mb most video size is 300mb so how can i dowload the images and video related to this size.
here i put my code so you can check it
HomeActivity.java
public class HomeActivity extends Activity
{
ProgressDialog progressdialog;
ArrayList<HashMap<String,String>> myplaylist = new ArrayList<HashMap<String,String>>();
String filename="";
int count=0;
PowerManager pm;
WakeLock wl;
ImageView imageview;
VideoView videoview;
int length=0;
int i=0;
boolean video=false;
private final int TIMEOUT_CONNECTION = 10000;//5sec
private final int TIMEOUT_SOCKET = 10000;//30sec
#SuppressLint("Wakelock")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
imageview=(ImageView)findViewById(R.id.imageview);
videoview=(VideoView)findViewById(R.id.videoview);
pm = (PowerManager)getApplicationContext().getSystemService(
getApplicationContext().POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "WakeLockOn");
wl.acquire();
HashMap<String, String> map = new HashMap<String, String>();
map.put("image","http://pr83.webofficeserver.info/img/sliderimg/original/1387205637Desertkp123-232.jpg");
map.put("type","video");
myplaylist.add(map);
HashMap<String, String> map2 = new HashMap<String, String>();
map2.put("image","http://pr83.webofficeserver.info/img/thumbnails/video/dummy.mov");
map2.put("type","image");
myplaylist.add(map2);
HashMap<String, String> map3 = new HashMap<String, String>();
map3.put("image","http://pr83.webofficeserver.info/img/sliderimg/original/1387206137planet-earth-in-space.jpg");
map3.put("type","video");
myplaylist.add(map3);
HashMap<String, String> map4 = new HashMap<String, String>();
map4.put("image","http://pr83.webofficeserver.info/img/thumbnails/video/BrandHi-240.mp4");
map4.put("type","video");
myplaylist.add(map4);
new DownloadFileFromURL().execute(myplaylist.get(count).get("image").toString());
}
// For Download File From Url
public class DownloadFileFromURL extends AsyncTask<String, String, String>
{
private final int TIMEOUT_CONNECTION = 10000;//5sec
private final int TIMEOUT_SOCKET = 10000;//30sec
#Override
protected void onPreExecute()
{
progressdialog=ProgressDialog.show(HomeActivity.this, "","Please Wait");
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/montorwerbung").mkdirs();
URL url = new URL(f_url[0]);
Uri u = Uri.parse(f_url[0]);
File f1 = new File("" + u);
filename=f1.getName();
File file = new File(root + "/montorwerbung" , filename);
Log.e("File Download Sdcard Filename","--->"+filename);
Log.e("File Download Sdcard Path","--->"+file.toString());
long startTime = System.currentTimeMillis();
//Open a connection to that URL.
URLConnection ucon = url.openConnection();
//this timeout affects how long it takes for the app to realize there's a connection problem
// ucon.setReadTimeout(TIMEOUT_CONNECTION);
// ucon.setConnectTimeout(TIMEOUT_SOCKET);
//Define InputStreams to read from the URLConnection.
// uses 3KB download buffer
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 1024);
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[10 * 1024];
//Read bytes (and store them) until there is nothing more to read(-1)
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff,0,len);
}
//clean up
outStream.flush();
outStream.close();
inStream.close();
} catch (Exception e)
{
Log.e("Download file frp, server Exception", "Exception : "
+ e.getMessage(), e);
//Log.e("Error: ",+e.printStackTrace());
}
return null;
}
#Override
protected void onPostExecute(String file_url)
{
if(progressdialog.isShowing())
{
progressdialog.dismiss();
}
Log.e("Count: ","----->"+count);
count++;
if(count<myplaylist.size())
{
new DownloadFileFromURL2().execute(myplaylist.get(count).get("image").toString());
}
else
{
wl.release();
Log.e("No More Downloads","--->");
}
}
}
class DownloadFileFromURL2 extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
progressdialog=ProgressDialog.show(HomeActivity.this, "","Please Wait");
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/montorwerbung").mkdirs();
URL url = new URL(f_url[0]);
Uri u = Uri.parse(f_url[0]);
File f1 = new File("" + u);
filename=f1.getName();
File file = new File(root + "/montorwerbung" , filename);
Log.e("File Download Sdcard Filename","--->"+filename);
Log.e("File Download Sdcard Path","--->"+file.toString());
long startTime = System.currentTimeMillis();
//Open a connection to that URL.
URLConnection ucon = url.openConnection();
//Define InputStreams to read from the URLConnection.
// uses 3KB download buffer
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 10);
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[10 * 1024];
//Read bytes (and store them) until there is nothing more to read(-1)
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff,0,len);
}
//clean up
outStream.flush();
outStream.close();
inStream.close();
} catch (Exception e)
{
Log.e("Download file frp, server Exception", "Exception : "
+ e.getMessage(), e);
//Log.e("Error: ",+e.printStackTrace());
}
return null;
}
#Override
protected void onPostExecute(String file_url)
{
if(progressdialog.isShowing())
{
progressdialog.dismiss();
}
count++;
Log.e("Count: ","----->"+count);
if(count<myplaylist.size())
{
new DownloadFileFromURL().execute(myplaylist.get(count).get("image").toString());
count++;
}
else
{
wl.release();
Log.e("No More Downloads 2","--->");
}
}
}

Categories

Resources