My app is a media player, it plays media by downloading the appropriate files from the Internet. I am using AsyncTask to do this, however the task takes longer to execute when multiple files need to be downloaded which results in a media player delay.
The desired behavior is to start playing a file after it has been downloaded while continuing to download any other files.
My code is as follows:
public class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
private String folder;
private ProgressDialog mProgressDialog;
private int noOfURLs;
private int noUrlLoad;
public DownloadTask(Context context, String folder, ProgressDialog mProgressDialog) {
this.context = context;
this.folder = folder;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
noOfURLs = sUrl.length;
for (int i = 0; i < sUrl.length; i++) {
URL url = new URL(sUrl[i]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Máy chủ trả về HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + folder + "/File" + (i + 1) + "." + sUrl[i].charAt(sUrl[i].length() - 3) + sUrl[i].charAt(sUrl[i].length() - 2) + sUrl[i].charAt(sUrl[i].length() - 1));
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
noUrlLoad++;
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context, context.getString(R.string.error) + result, Toast.LENGTH_LONG).show();
}
}
Inside your doInBackground method, call publishProgress(Integer) to send your updates to the UI thread. This will trigger the onProgressUpdate method to be called, and you'll be able to see when the first download has finished.
http://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...)
I have an android app which downloads a video by clicking a button and saves it on user's device. when users click on the button the app checks if the video is in users' device, and if it is not it downloads the video and if it has been downloaded the app just plays the video without the need to download.
However when the download crashes the file is there , but the app can't plays it and gets tricked that the file has been downloaded already.
I wanted to ask if there are any ways to check if the download process has crashed or the file is corrupted.
Thanks
You can use AsyncTask as below to check if the download was interupted or not.
Below code is just for example purpose
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
initialText.setText(getString(R.string.connecting));
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String fileURL = f_url[0];
if (fileURL.contains(" ")) {
fileURL = fileURL.replace(" ", "%20");
}
URL url = new URL(fileURL);
filename = f_url[0].substring(fileURL.lastIndexOf("/") + 1);
URLConnection connection = url.openConnection();
connection.connect();
// getting file length
int lengthOfFile = connection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File file = new File(FilePath);
if (!file.exists()) {
if (!file.isDirectory()) {
file.mkdirs();
}
}
// Output stream to write file
OutputStream output = new FileOutputStream(FilePath + filename);
byte data[] = new byte[1024];
long total = 0;
runOnUiThread(new Runnable() {
#Override
public void run() {
setSubTitle(getString(R.string.downloading));
initialText.setText(ad_tv_initialText.getText().toString() + getString(R.string.connected));
}
});
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
return "SUCCESS";
} catch (Exception e) {
return "FAILED";
}
}
protected void onProgressUpdate(String... progress) {
progress.setProgress(Integer.parseInt(progress[0]));
progressText.setText(progress[0] + " %");
}
#Override
protected void onPostExecute(String result) {
if (result.equals("SUCCESS")) {
takeDecisionToPlay();
} else if (result.equals("FAILED")) {
setSubTitle(getString(R.string.failed_));
finalText.setText(getString(R.string.failed));
}
}
}
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);
I am trying to call an Restful api using following code. Now I want to show the progress(% of download). Is it at all possible? If, what change in code is needed for that?
BufferedReader reader=null;
try{
URL mUrl = new URL("http://dev.amazaws.com/formservice/rest/v1/registrationreports/registrationsbyproduct/132866/");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write( data );
writer.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
}
String res = sb.toString();
}catch(Exception ex){
}finally{
try{
reader.close();
}catch(Exception ex) {}
}
Try this code, i have implemented this code in one of my application! You can get the idea how to show the percentage! and well This code actually download the JSON from server and saves it on mobile device.
public class LoginActivity extends Activity {
private ProgressDialog prgDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
}
// Button Click function, on which you want to make restApi call
public void buttonClicked(View view){
new PrefetchData().execute();
}
private class PrefetchData extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// before making http calls
prgDialog = new ProgressDialog(LoginActivity.this);
prgDialog.setMessage("Downloading Data. Please wait...");
prgDialog.setIndeterminate(false);
prgDialog.setMax(100);
prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
prgDialog.setCancelable(false);
prgDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://xyz/testJSON");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
// Show ERROR
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
String extPath = Environment.getExternalStorageDirectory() + "/" + FILE_PATH;
// Environment.
File file = new File(extPath);
if(!file.exists()){
file.createNewFile();
}
output = new FileOutputStream(extPath);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (fileLength > 0){
// only if total length is known
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// After completing http call
// will close this activity and lauch main activity
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
//Update the progress
#Override
protected void onProgressUpdate(Integer... values)
{
prgDialog.setProgress(values[0]);
}
}
As stated in this question you most often wont know the size of the stream in advance https://stackoverflow.com/a/1119346/2122552
The stated answer also links to an api to get Filesizes. But with a RESTful API you usually dont know the exact size of the Inputstream.
But, however, if you know the size you can break it down to use 100 as 100% and calculate the progress as (downloadedBytes/fileSizeInBytes * 100). Otherwise just use an indeterminate ProgressBar.
You can check the case and make the progressbar indeterminate when you dont know the size of the answer, and otherwise calculate the progress and update it like shown in the official documentation
I want to implement autoupdate for my app.
I used the DownloadManager (and now an AsyncTask for download) and install the file.
The download is working fine. On the PostExecute I fire an intent to install the new apk. Everytime i got a parsing error.
When I open the file in ES File Explorer, I am able to install it successfully, but not within the app and the intent.
I even changed from /Android/data/packagename/files to /Download but still not working.
PS: i know the code is dirty, but working, and I changed so often so many thinks to get it work, but it doesnt...
public class UpdateAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(LoginActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
protected String doInBackground(String... arg0) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
//URL url = new URL(arg0[0]);
URL url = new URL(apkUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
//output = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "Straffv2.apk");
output = new FileOutputStream("/storage/emulated/0/Download/Straffv2.apk");
File outputFile = new File(Environment.DIRECTORY_DOWNLOADS, "Straffv2.apk");
outputFile.setReadable(true, false);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
protected void onPostExecute(String result){
mProgressDialog.dismiss();
if (result != null) {
//Toast.makeText(LoginActivity.this,"Download error: "+result, Toast.LENGTH_LONG).show();
}
else {
//Toast.makeText(LoginActivity.this,"File downloaded", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS, "Straffv2.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
LoginActivity.this.startActivity(intent);
}
}
}