How to show upload Progress for multiple uploads separately - Android - 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

Related

Getting java.net.SocketTimeoutException alwayse in downloading files with OkHttp

I am using OkHttp to download a file from the server.
And this is my code:
I set read and write timeout for it:
public static final String API_BASE_URL = "http://XXXX:8080/tablet/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.connectTimeout(60,TimeUnit.SECONDS)
.writeTimeout(60,TimeUnit.SECONDS);
This is my createServiceFile:
public static <S> S createServiceFile(Class<S> serviceClass, final String token) {
if (token != null) {
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", token)
.header("Accept", "text/html,application/xhtml+xml,application/pdf,application/xml;q=0.9," +
"image/webp,audio/mpeg ,image/png,audio/mp4,image/jpeg,*/*;q=0.8")
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
And this is my code that I write the response to SD Card (in response contentLength is -1 because the server doesn't send it to me):
public DownloadRequest DownloadFile() {
//Creating folder for Application in SD Card if it's not created yet in App Class!
new java.io.File(G.DIR_APP).mkdirs();
new java.io.File(G.DIR_MEDIA).mkdirs();
APIService downloadService = ServiceGenerator.createServiceFile(APIService.class, G.TOKEN);
downloadService.downloadFileWithDynamicUrlSync(url)//set URL of the file
.subscribeOn(Schedulers.newThread())
.observeOn(Schedulers.io())
.delay(30, TimeUnit.MILLISECONDS)
.subscribe(new Observer<ResponseBody>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(ResponseBody responseBody) {
Log.i(TAG, "On Next And Current App is: " + fileName);
if (writeResponseBodyToDisk(responseBody)) {
Log.i(TAG, fileName + "Downloaded successful");
//This Download was successful Then try to set downloadResult true
result = true;
} else {
result = false;
}
}
#Override
public void onError(Throwable e) {
Log.i(TAG, "!!!!!!!!!!!!!!!!\n\nOn Error And Current App is: " +
fileName + " And Error is" + e.toString() + "\n\n!!!!!!!!!!!!!!!!\n\n");
//Set downloadResult false
result = false;
if (listener != null) {
listener.onDownloadCompleteListener(false);
}
}
#Override
public void onComplete() {
Log.i(TAG, "On Complete And Current App is: " + fileName);
if (listener != null) {
if (result) {
listener.onDownloadCompleteListener(true);
} else {
listener.onDownloadCompleteListener(false);
}
}
}
});
return this;
}
And this code will write response to disck:
private boolean writeResponseBodyToDisk(ResponseBody body) {
// Location to save downloaded file and filename
java.io.File file = new java.io.File(destinationPath + fileName + "." + extension);
try {
InputStream inputStream = null;
OutputStream outputStream = null;
int bytesBuffered = 0;
try {
byte[] fileReader = new byte[bufferSize];
downloadSize = 0;
inputStream = body.byteStream();
/*
* If append requested we have to append new bytes to
* Exists bytes on the storage
*/
if (appendNeed) {
outputStream = new FileOutputStream(file, true);
} else {
outputStream = new FileOutputStream(file);
}
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
bytesBuffered += read;
if (bytesBuffered > 1024 * 1024) {
// outputStream.write(fileReader, 0, read);
outputStream.flush();
bytesBuffered = 0;
}
outputStream.write(fileReader, 0, read);
downloadSize += read;
percent = (int) (100.0f * (float) downloadSize / totalSize);
if (listener != null) {
listener.onDownloadPercentListener(percent);
}
}
outputStream.flush();
inputStream.close();
outputStream.close();
return true;
} catch (IOException e) {
Log.i(TAG, "Error in download" + e.toString());
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
Log.i(TAG, "Error in download" + e.toString());
return false;
}
}
But I get false from this method (writeResponseBodyToDisk)with error of
java.net.SocketTimeoutException while the file is downloaded correctly!
I think this problem it about contentLength that is -1 for me.
Thank you for your answers.

How to Show Progress Bar while uploading with percentage

I am uploading video and photo.and its working fine .now i want to show progress bar while uploading data with percentage.i took reference from android hive and its implemented in httpclient and i modified it accordingly httpurlconnection.Any help will appreciated .thank you.
This is my main Activity where async task is performing.
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
String charset = "UTF-8";
String requestURL = "YOUR_URL";
VideoUpload multipart = null;
try {
multipart = new VideoUpload(Config.FILE_UPLOAD_URL, charset);
} catch (IOException e) {
e.printStackTrace();
}
{
//========================================================
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
//========================================================
multipart.addFormField("website", "www.androidhive.info");
multipart.addFormField("email", "abc#gmail.com");
try {
multipart.addFilePart("image", new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
try {
List<String> response = multipart.finish(); // response from server.
} catch (IOException e) {
e.printStackTrace();
}
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
this is my uploding class for httpurlconnections and its working .
public VideoUpload(String requestURL, String charset)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* 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
*/
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("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
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 List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
here i took progress bar class from androidhive but i don't know how to use it
public class AndroidMultiPartEntity extends MultipartEntity
{
private final ProgressListener listener;
public AndroidMultiPartEntity(final ProgressListener listener) {
super();
this.listener = listener;
}
public AndroidMultiPartEntity(final HttpMultipartMode mode,
final ProgressListener listener) {
super(mode);
this.listener = listener;
}
public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary,
final Charset charset, final ProgressListener listener) {
super(mode, boundary, charset);
this.listener = listener;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, this.listener));
}
public static interface ProgressListener {
void transferred(long num);
}
public static class CountingOutputStream extends FilterOutputStream {
private final ProgressListener listener;
private long transferred;
public CountingOutputStream(final OutputStream out,
final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}
public void write(int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}
There is progressUpdate method in AsyncTask class, which will return you progress of file uploading, here is my code which might help you out.
private final ProgressDialog mDialog;
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading " + file.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
mRequest.abort();
}
});
mDialog.show();
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
mDialog.setProgress(percent);
}

Download a file with no extension from a server

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);

Android: access thread from class

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.

Upload of some file fails using HttpClient

I am trying to upload images as well as videos to my external server from the app. I Googled and found out HttpClient procedure is a good one, so I downloaded the library and execute the following code which normally works well for every file however for some videos, it does not upload the video.
public void executeMultipartPost(String uri) throws Exception {
try {
File file = new File(uri);
Uri imageUri = Uri.fromFile(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = readBytes(imageUri);
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://example.com/ccs-business/upload.php");
ByteArrayBody bab = new ByteArrayBody(data, file.getName());
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded_video", bab);
reqEntity.addPart("number", new StringBody("123456"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
Log.v("ONMESSAGE", "Response: " + s);
dialog.dismiss();
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
dialog.dismiss();
}
}
public byte[] readBytes(Uri uri) throws IOException {
InputStream inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
My requirement is to upload up to 20mb file.
I Have tired Uploading files with below code attached and worked fine :
public class UploadService extends IntentService {
/**
* Utility method that creates the intent that starts the background
* file upload service.
*
* #param task object containing the upload request
* #throws IllegalArgumentException if one or more arguments passed are invalid
* #throws MalformedURLException if the server URL is not valid
*/
public static void startUpload(final UploadRequest task)
throws IllegalArgumentException, MalformedURLException {
if (task == null) {
throw new IllegalArgumentException("Can't pass an empty task!");
} else {
task.validate();
final Intent intent = new Intent(UploadService.class.getName());
intent.setAction(ACTION_UPLOAD);
intent.putExtra(PARAM_NOTIFICATION_CONFIG, task.getNotificationConfig());
intent.putExtra(PARAM_ID, task.getUploadId());
intent.putExtra(PARAM_URL, task.getServerUrl());
intent.putExtra(PARAM_METHOD, task.getMethod());
intent.putParcelableArrayListExtra(PARAM_FILES, task.getFilesToUpload());
intent.putParcelableArrayListExtra(PARAM_REQUEST_HEADERS, task.getHeaders());
intent.putParcelableArrayListExtra(PARAM_REQUEST_PARAMETERS, task.getParameters());
task.getContext().startService(intent);
}
}
public UploadService() {
super(SERVICE_NAME);
}
#Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new NotificationCompat.Builder(this);
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_UPLOAD.equals(action)) {
notificationConfig = intent.getParcelableExtra(PARAM_NOTIFICATION_CONFIG);
final String uploadId = intent.getStringExtra(PARAM_ID);
final String url = intent.getStringExtra(PARAM_URL);
final String method = intent.getStringExtra(PARAM_METHOD);
final ArrayList<FileToUpload> files = intent.getParcelableArrayListExtra(PARAM_FILES);
final ArrayList<NameValue> headers = intent.getParcelableArrayListExtra(PARAM_REQUEST_HEADERS);
final ArrayList<NameValue> parameters = intent.getParcelableArrayListExtra(PARAM_REQUEST_PARAMETERS);
lastPublishedProgress = 0;
wakeLock.acquire();
try {
createNotification();
handleFileUpload(uploadId, url, method, files, headers, parameters);
} catch (Exception exception) {
broadcastError(uploadId, exception);
} finally {
wakeLock.release();
}
}
}
}
private void handleFileUpload(final String uploadId,
final String url,
final String method,
final ArrayList<FileToUpload> filesToUpload,
final ArrayList<NameValue> requestHeaders,
final ArrayList<NameValue> requestParameters)
throws IOException {
final String boundary = getBoundary();
final byte[] boundaryBytes = getBoundaryBytes(boundary);
HttpURLConnection conn = null;
OutputStream requestStream = null;
try {
conn = getMultipartHttpURLConnection(url, method, boundary);
setRequestHeaders(conn, requestHeaders);
requestStream = conn.getOutputStream();
setRequestParameters(requestStream, requestParameters, boundaryBytes);
uploadFiles(uploadId, requestStream, filesToUpload, boundaryBytes);
final byte[] trailer = getTrailerBytes(boundary);
requestStream.write(trailer, 0, trailer.length);
final int serverResponseCode = conn.getResponseCode();
final String serverResponseMessage = conn.getResponseMessage();
broadcastCompleted(uploadId, serverResponseCode, serverResponseMessage);
} finally {
closeOutputStream(requestStream);
closeConnection(conn);
}
}
private String getBoundary() {
final StringBuilder builder = new StringBuilder();
builder.append("---------------------------")
.append(System.currentTimeMillis());
return builder.toString();
}
private byte[] getBoundaryBytes(final String boundary)
throws UnsupportedEncodingException {
final StringBuilder builder = new StringBuilder();
builder.append(NEW_LINE)
.append(TWO_HYPHENS)
.append(boundary)
.append(NEW_LINE);
return builder.toString().getBytes("US-ASCII");
}
private byte[] getTrailerBytes(final String boundary)
throws UnsupportedEncodingException {
final StringBuilder builder = new StringBuilder();
builder.append(NEW_LINE)
.append(TWO_HYPHENS)
.append(boundary)
.append(TWO_HYPHENS)
.append(NEW_LINE);
return builder.toString().getBytes("US-ASCII");
}
private HttpURLConnection getMultipartHttpURLConnection(final String url,
final String method,
final String boundary)
throws IOException {
final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setChunkedStreamingMode(0);
conn.setRequestMethod(method);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
return conn;
}
private void setRequestHeaders(final HttpURLConnection conn,
final ArrayList<NameValue> requestHeaders) {
if (!requestHeaders.isEmpty()) {
for (final NameValue param : requestHeaders) {
conn.setRequestProperty(param.getName(), param.getValue());
}
}
}
private void setRequestParameters(final OutputStream requestStream,
final ArrayList<NameValue> requestParameters,
final byte[] boundaryBytes)
throws IOException, UnsupportedEncodingException {
if (!requestParameters.isEmpty()) {
for (final NameValue parameter : requestParameters) {
requestStream.write(boundaryBytes, 0, boundaryBytes.length);
byte[] formItemBytes = parameter.getBytes();
requestStream.write(formItemBytes, 0, formItemBytes.length);
}
}
}
private void uploadFiles(final String uploadId,
final OutputStream requestStream,
final ArrayList<FileToUpload> filesToUpload,
final byte[] boundaryBytes)
throws UnsupportedEncodingException,
IOException,
FileNotFoundException {
final long totalBytes = getTotalBytes(filesToUpload);
long uploadedBytes = 0;
for (FileToUpload file : filesToUpload) {
requestStream.write(boundaryBytes, 0, boundaryBytes.length);
byte[] headerBytes = file.getMultipartHeader();
requestStream.write(headerBytes, 0, headerBytes.length);
final InputStream stream = file.getStream();
byte[] buffer = new byte[BUFFER_SIZE];
long bytesRead;
try {
while ((bytesRead = stream.read(buffer, 0, buffer.length)) > 0) {
requestStream.write(buffer, 0, buffer.length);
uploadedBytes += bytesRead;
broadcastProgress(uploadId, uploadedBytes, totalBytes);
}
} finally {
closeInputStream(stream);
}
}
}
private long getTotalBytes(final ArrayList<FileToUpload> filesToUpload) {
long total = 0;
for (FileToUpload file : filesToUpload) {
total += file.length();
}
return total;
}
private void closeInputStream(final InputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (Exception exc) { }
}
}
private void closeOutputStream(final OutputStream stream) {
if (stream != null) {
try {
stream.flush();
stream.close();
} catch (Exception exc) { }
}
}
private void closeConnection(final HttpURLConnection connection) {
if (connection != null) {
try {
connection.disconnect();
} catch (Exception exc) { }
}
}
private void broadcastProgress(final String uploadId, final long uploadedBytes, final long totalBytes) {
final int progress = (int) (uploadedBytes * 100 / totalBytes);
if (progress <= lastPublishedProgress) return;
lastPublishedProgress = progress;
updateNotificationProgress(progress);
final Intent intent = new Intent(BROADCAST_ACTION);
intent.putExtra(UPLOAD_ID, uploadId);
intent.putExtra(STATUS, STATUS_IN_PROGRESS);
intent.putExtra(PROGRESS, progress);
sendBroadcast(intent);
}
private void broadcastCompleted(final String uploadId, final int responseCode, final String responseMessage) {
final String filteredMessage;
if (responseMessage == null) {
filteredMessage = "";
} else {
filteredMessage = responseMessage;
}
if (responseCode >= 200 && responseCode <= 299)
updateNotificationCompleted();
else
updateNotificationError();
final Intent intent = new Intent(BROADCAST_ACTION);
intent.putExtra(UPLOAD_ID, uploadId);
intent.putExtra(STATUS, STATUS_COMPLETED);
intent.putExtra(SERVER_RESPONSE_CODE, responseCode);
intent.putExtra(SERVER_RESPONSE_MESSAGE, filteredMessage);
sendBroadcast(intent);
}
private void broadcastError(final String uploadId, final Exception exception) {
updateNotificationError();
final Intent intent = new Intent(BROADCAST_ACTION);
intent.setAction(BROADCAST_ACTION);
intent.putExtra(UPLOAD_ID, uploadId);
intent.putExtra(STATUS, STATUS_ERROR);
intent.putExtra(ERROR_EXCEPTION, exception);
sendBroadcast(intent);
}
private void createNotification() {
notification.setContentTitle(notificationConfig.getTitle())
.setContentText(notificationConfig.getMessage())
.setSmallIcon(notificationConfig.getIconResourceID())
.setProgress(100, 0, true)
.setOngoing(true);
startForeground(UPLOAD_NOTIFICATION_ID, notification.build());
}
private void updateNotificationProgress(final int progress) {
notification.setContentTitle(notificationConfig.getTitle())
.setContentText(notificationConfig.getMessage())
.setSmallIcon(notificationConfig.getIconResourceID())
.setProgress(100, progress, false)
.setOngoing(true);
startForeground(UPLOAD_NOTIFICATION_ID, notification.build());
}
private void updateNotificationCompleted() {
stopForeground(notificationConfig.isAutoClearOnSuccess());
if (!notificationConfig.isAutoClearOnSuccess()) {
notification.setContentTitle(notificationConfig.getTitle())
.setContentText(notificationConfig.getCompleted())
.setSmallIcon(notificationConfig.getIconResourceID())
.setProgress(0, 0, false)
.setOngoing(false);
notificationManager.notify(UPLOAD_NOTIFICATION_ID_DONE, notification.build());
}
}
private void updateNotificationError() {
stopForeground(false);
notification.setContentTitle(notificationConfig.getTitle())
.setContentText(notificationConfig.getError())
.setSmallIcon(notificationConfig.getIconResourceID())
.setProgress(0, 0, false)
.setOngoing(false);
notificationManager.notify(UPLOAD_NOTIFICATION_ID_DONE, notification.build());
}
}
For compelete Source code refer this

Categories

Resources