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...)
Related
I am trying to download a file from an online source of mine. The issue I am having is that the browser window keeps appearing as it load into the download server. Is there some way that I may be able to hide this? I already have this code below in the doInBackground portion of an AsyncTask, but cant seem to get it to hide the browser bar. Here is my code at this point:
private class getErDone extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setTitle("Downloading Software");
progressDialog.setMessage("Now Updating, DO NOT TURN OFF DEVICE");
progressDialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try{
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("http://mydownloadlink.com/myfile?dl=1"));
//**Note** As convincing as it seems, this is not the real download link
startActivity(goToMarket);
}catch (UnknownError e){
e.printStackTrace();
}
/*catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException t){
t.printStackTrace();
}*/
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
Thanks everyone!
here is sample from my code, download without browser:
private TextView mFileDownloadProgressBarPercent;
private ProgressBar mFileDownloadProgressBar;
private Runnable mFileExecutionTaskAfterDownload;
public String fileDownloadedResultPath;
and asynctask:
class DownloadFileFromURL extends AsyncTask<String, String, String> {
// Before starting background thread
// Show Progress Bar Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.VISIBLE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.VISIBLE);
}
// Downloading file in background thread
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf"); // for example we are downloading pdf's so store in pdf dir.
folder.mkdir();
File subFolder = new File(extStorageDirectory+"/pdf", "fileId"); // here you can place files by id of category etc..
subFolder.mkdir();
String fileName = url.toString().substring(url.toString().lastIndexOf("/")+1);
fileDownloadedResultPath = subFolder + "/" + fileName;
// Output stream to write file
OutputStream output = new FileOutputStream(subFolder + "/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setProgress(Integer.parseInt(progress[0]));
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setText(mContext.getString(R.string.downloading_file) + " " + String.format("%s%%",Integer.parseInt(progress[0])+""));
}
#Override
protected void onPostExecute(String file_url) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.GONE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.GONE);
if(mFileExecutionTaskAfterDownload != null)
mFileExecutionTaskAfterDownload.run();
}
}
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 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);
}
}
}
I want to download some files from url to refresh my app but I don´t know what is the best way to do this. I have this code to download one file but when I download more than one sometimes gives me an error. Is it possible to do the download in background without using Android Activity? Thank you
class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#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();
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]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Error en la descarga: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"Programa actualizado correctamente", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
fOut = openFileOutput("example.json",MODE_PRIVATE);
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));
fOut.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (fOut != null)
fOut.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
and I call to this task with:
downloadTask.execute("myurl");
private class DownloadAsynkTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
// progress dialog
}
#Override
protected Integer doInBackground(String... urls) {
HttpURLConnection connection = null;
InputStream is = null;
for (int i=0; i< urls.length; i++) {
try {
URL url = new URL(urls[i]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return connection.getResponseCode();
} else {
is = connection.getInputStream();
}
// do something whit url data (add it to list maybe)
if (connection != null) {
connection.disconnect();
}
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
// OK
} else {
}
}
}
and call it whit String[] urls
new DownloadAsynkTask().execute(urls);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have created an android app. That needs to download pdf, audio and video files from my asp.net web api to my android application. But I dont have an idea of how my web api code would be like and my android download code for pdf, audio files and video files would look like.
Thanks for your perusal.
You can customize and use this, you will need the wakelock permission to prevent interruption
#SuppressLint("Wakelock")
public class DownloadTask extends AsyncTask<String, Integer, String>
{
private Context context;
public DownloadTask(Context context ,Dialog dialog, ProgressBar progressBar ,TextView progressTextView , String destinationPath ,String fileName , JSONObject jObject )
{
this.context = context;
}
#SuppressWarnings("resource")
#Override
protected String doInBackground(String... sUrl)
{
String directory = sUrl[0];
String fileName = sUrl[1];
//prevent CPU from going off if the user presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
wl.acquire();
//download
try
{
new File(directory).mkdirs();
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try
{
//connect to url
URL url = new URL(sUrl[2]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// check for http_ok (200)
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP "
+ connection.getResponseCode() + " "
+ connection.getResponseMessage();
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(directory+"/"+fileName+".mp3");//change extension
//copying
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1)
{
// allow canceling
if (isCancelled())
{
new File(directory+"/"+fileName+".mp3").delete();//delete partially downloaded file
return null;
}
total += count;
if (fileLength > 0 ) //publish progress only if total length is known
publishProgress( (int)(total/1024) , fileLength/1024 );//(int) (total * 100 / fileLength));
output.write(data, 0, count);
}
}
catch (Exception e)
{
return e.toString();
}
finally //closing streams and connection
{
try
{
if (output != null)
output.close();
if (input != null)
input.close();
}
catch (IOException ignored)
{
}
if (connection != null)
connection.disconnect();
}
}
finally
{
wl.release(); // release the lock screen
}
return null;
}
#Override // onPreExecute and onProgressUpdate run on ui thread so you can update ui from here
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress)
{
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result)
{
if (result != null)
Toast.makeText(context, "Download error: " + result,Toast.LENGTH_SHORT).show();
else
{
Toast.makeText(context, " download complete ",Toast.LENGTH_SHORT).show();
}
}
}
and then call it from main
new DownloadTask(this).execute( dirPath , fileName , urlToDownload );