how to download file in android download service - android

i have this url http://translate.google.com/translate_tts?ie=UTF-8&q=hi&tl=en&total=1&idx=0&textlen=2
when i place it to pc and android browser it makes me force to download
how can i make it download in my android application without browser.
i tried to make to download using this tutorial how can i download audio file from server by url
.but it did not work.
anyone please help
Thank you Kristijana Draca think it is working but where it save in emulator here is my code public class Main extends Activity {
EditText inputtext;
Button listen;
Button shareButton;
TextView tv;
ProgressBar proBar;
//ProgressDialog progress;
MediaPlayer player;
public Boolean isPlaying=true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadContent();
}
private void downloadContent() {
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http://translate.google.com/translate_a/t?client=t&source=baf&sl=ar&tl=en&hl=en&q=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&sc=1 ");
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(
connection.getInputStream());
// Create db
OutputStream output = new FileOutputStream(
Environment.getDataDirectory() + "/data/"
+ "com.jony.com" + "/file.mp3");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
Toast.makeText(getApplicationContext(), "download complete", 1000).show();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "download complete", 1000).show();
}
}
});

You can download any file using AsyncTask.
downloadContent();
private void downloadContent() {
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http://somehost.com/file.mp3");
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(
connection.getInputStream());
// Create db
OutputStream output = new FileOutputStream(
Environment.getDataDirectory() + "/data/"
+ PACKAGE_NAME + "/file.mp3");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}

Related

Delete file if AsyncTask Fail

Currently
I am downloading a file from a URL, I'm doing this within AsyncTask inside a Adapter. The problem I have is that when I press back onBackPressed the download stops but the file remains in the folder FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/file.mp4");
My Question
Is it possible to delete the file if AsyncTask does not complete?
I have tried to do file.delete(); in the catch of doinbackground but I get error file.delete(); is ignored
Here is a summary of my adapter----
When Item in holder is clicked I call AsyncTask:
holder.setItemClickListener(new ItemClickListener() {
if (pos == 1) {
if(manager.fetchVideoPath(pos)==null) {
DownloadFileFromURL p = new DownloadFileFromURL();
p.execute(pos + "", "https://www.dropbox.com/s/xnzw753f13k68z4/Piper%20First%20Look%20%282016%29%20-%20Pixar%20Animated%20Short%20HD.mp4?dl=1");
a = "one";
bars.set(pos,new ProgressModel(pos,1));
//This is what is causing the issue
RecyclerVideoAdapter.this.notifyItemChanged(pos);
}
My AsyncTask:
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
((CircularProgressBar)vview.findViewById(R.id.circularProgressBar)).setProgress(1);
}
#Override
protected String doInBackground(String... f_url) {
int count;
String pathreference = f_url[0]+",";
positionnumber = Integer.parseInt(f_url[0]);
try {
URL url = new URL(f_url[1]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
if (a.equals("one")) {
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/file.mp4");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
pathreference = pathreference+Environment.getExternalStorageDirectory().toString()+"/file.mp4";
output.close();
input.close();
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return pathreference;
}
protected void onProgressUpdate(String... progress) {
bars.get(positionnumber).setProgress_(Float.parseFloat(progress[0]));
((CircularProgressBar)vview.findViewById(R.id.circularProgressBar)).setProgress(bars.get(positionnumber).getProgress_());
}
#Override
protected void onPostExecute(String file_url) {
String []split = file_url.split(",");
int index1 = Integer.parseInt(split[0]);
videoHolderClass.set(index1,new VideoHolderClass(index1,imgres[0]));
bars.get(index1).setProgress_(0);
manager.insertVideoPath(index1+"",split[1]);
RecyclerVideoAdapter.this.notifyItemChanged(index1);
}
}
Building on the answer on this post, try to put the logic of deleting the file inside isCancelled() like this:
if (isCancelled() && file.exists())
file.delete();
else
{
// do your work here
}
Then you can call p.cancel(true) inside onBackPressed

Android to download a Zip file

I'm trying to download a zip file from an API. For this purpose I'm using this following code:
public class Download_Activity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
startBtn = (Button) findViewById(R.id.downloadButton);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = downloadURL;
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.connect();
Log.i("1111", "1111" );
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot, "hello1.zip");
Log.i("2222", "2222" );
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
Log.i("3333", "3333" );
Log.i("befferLength", "bufferLength: " + bufferLength);
Log.i("is read buffer", "is read buffer: " + inputStream.read(buffer));
while ((bufferLength = inputStream.read(buffer)) > 0) {
Log.i("inside while", "inside while ");
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
updateProgress(downloadedSize, totalSize);
}
Log.i("4444", "4444" );
fileOutput.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
public void updateProgress(int currentSize, int totalSize) {
Toast.makeText(getApplicationContext(), "Loading Files...",
Toast.LENGTH_SHORT).show();
}
In this code, the zip file is created as "hello1.zip" but this file is empty in my mobile. Here I've various log statements to find the execution of code. To my surprise only upto "Log.i("2222", "2222" );" is printed while the rest of the logs are not printed. Can you please tell me what the problem is???
Thanks in advance..!
U can use DownloadManager class for this purpose it handles the pause and continues the dowloading in the case of network availablity and you can run a broadcast reciver to perform you actions( like pushing a notification etc) when dowloading is complete
http://developer.android.com/reference/android/app/DownloadManager.html

android :: show progress dialog till asynctask does not get complete

I am downloading a zip file of 15 mb and then unzip it in the sd card.
I am using progress dialog to show the status. First time it works perfectly, and when I change the db version number on server to download new file and start the app again then progress dialog disappears in between and causes crash in the app.
Below is the code.
class CheckInAppUpdatesAsyncTask extends AsyncTask<Void, Void, Void> {
Dialog progress;
#Override
protected Void doInBackground(Void... params) {
try {
downloadDB();
} catch (Exception e) {
}
}
#Override
protected void onPostExecute(final Void result) {
stopWorking();
}
#Override
protected void onPreExecute() {
startWorking();
}
};5
private void startWorking() {
synchronized (this.diagSynch) {
if (this.pDiag != null) {
this.pDiag.dismiss();
}
this.pDiag = ProgressDialog.show(Browse.context, "Working...",
"Please wait while we load the encyclopedia.", true, false);
}
}
private void stopWorking() {
synchronized (this.diagSynch) {
if (this.pDiag != null) {
this.pDiag.dismiss();
}
}
}
Download code
URL url = new URL(serverFileURL);
Log.d("FILE_URLLINK", "serverFileURL " + serverFileURL);
URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();
connection.getContentLength();
byte data[] = new byte[1024];
input = new GZIPInputStream(input);
InputSource is = new InputSource(input);
InputStream in = new BufferedInputStream(is.getByteStream());
String inAppDBName = Constants.NEW_DB_NAME_TO_DOWNLOAD;
OutputStream output = new BufferedOutputStream(new FileOutputStream(dir + "/" + inAppDBName));
int length;
while ((length = in.read(data)) > 0) {
output.write(data, 0, length);
}
output.flush();
output.close();
input.close();
Any idea?
You should put unzip code before stopWorking(); in onPostExecute.
It will not close till all things happen.

Android Async - Unzip after file download

I'm trying to create a method within my activity that will unzip the downloaded file to a certain directory. I have tried several different ways and haven't had much luck. I've seen some people use a separate class to do this task, I want to avoid doing that, but if it's my only option then I will do it. Here is my activity:
public class lava_parkour extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lava_parkour);
startBtn = (Button)findViewById(R.id.button1);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload(v);
} });
}
private void startDownload(View v) {
String url = "https://www.dropbox.com/s/lxnizie52efq3e8/lava%20parkour.zip?
dl=1";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new
FileOutputStream("/sdcard/games/com.mojang/lava_parkour.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Toast.makeText(lava_parkour.this, "Process completed! THis map has been added
to your game!", Toast.LENGTH_LONG).show();
}
}
}
Any help is appreciated!

Trying to get downloading file size, but get an error

private class DownloadLargeFileTask extends AsyncTask<Void, Void, Void>
{
private final ProgressDialog dialog;
public DownloadLargeFileTask(ProgressDialog dialog) {
this.dialog = dialog;
}
protected void onPreExecute() {
dialog.show();
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
#Override
protected Void doInBackground(Void... arg0) {
download();
return null;
}
}
private void download ()
{
try
{
long startTime = System.currentTimeMillis();
URL u = new URL("http://mds.podfm.ru/188/download/040_Sergejj_Palijj_-_Karantin_CHast_2.mp3");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File("/sdcard/","my.mp3"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int downloadedSize = 0;
while ( (len1 = in.read(buffer)) != -1 )
{
f.write(buffer,0, len1);
downloadedSize += len1;
ReturnDownloadedBytes(downloadedSize);
}
f.close();
Log.d("ImageManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
}
catch (IOException e)
{
Log.d("ImageManager", "Error" + ((System.currentTimeMillis()) / 1000) + e + " sec");
}
}
private void ReturnDownloadedBytes(int size)
{
text.setText(String.valueOf(size));
}
Error says: Only the original thread that created a view hierarchy can touch its views.
i think this means that i create textview from one therad and trying to get access from another one (AsyncTask) but how to get it?
Thanks
EDIT
here is the all code. but even if i send in publishProgress(downloadedSize) int value = 10 it alwys outputs in text.setText(String.valueOf(progress)); different values like [Ljava.lang.float;#43ed62f78
public class list extends Activity {
private TextView text;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.result);
}
public void selfDestruct(View view) {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("????????. ?????...");
new DownloadLargeFileTask(dialog).execute();
}
private class DownloadLargeFileTask extends AsyncTask<Void, Integer, Void>
{
private final ProgressDialog dialog;
public DownloadLargeFileTask(ProgressDialog dialog) {
this.dialog = dialog;
}
protected void onPreExecute() {
dialog.show();
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
protected void onProgressUpdate(Integer...progress) {
text.setText(String.valueOf(progress));
}
#Override
protected Void doInBackground(Void... arg0) {
try
{
long startTime = System.currentTimeMillis();
URL u = new URL("http://mds.podfm.ru/188/download/040_Sergejj_Palijj_-_Karantin_CHast_2.mp3");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File("/sdcard/","my.mp3"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int downloadedSize = 10;
while ( (len1 = in.read(buffer)) != -1 )
{
f.write(buffer,0, len1);
//downloadedSize += len1;
**publishProgress(downloadedSize);**
}
f.close();
Log.d("ImageManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
}
catch (IOException e)
{
Log.d("ImageManager", "Error" + ((System.currentTimeMillis()) / 1000) + e + " sec");
}
return null;
}
}
You are correct in your assessment of the error. I'm assuming that text is a TextView object that is defined in your Activity, and as such it is created in the UI thread. The code that runs within doInBackground() runs in a separate thread. Only the UI thread can perform updates to UI elements, so when you try to call setText you get the error message that you reported.
Abhinav is also correct in how to fix the issue, as AsyncTask has a method that you can call to send updates from the background thread to the UI thread: publishProgress, which calls onProgressUpdate().
Add this method to your AsyncTask:
#Override
protected void onProgressUpdate(Integer... integer){
text.setText(integer[0].toString());
}
And change the while loop in download():
while ( (len1 = in.read(buffer)) != -1 )
{
f.write(buffer,0, len1);
downloadedSize += len1;
publishProgress(downloadedSize);
}
You can change the UI by publishing the progress to the UI thread. Call publishProgress from doInBackground. This will call onProgressUpdate in your AsyncTask from where you can update the UI.
You will have to define onProgressUpdate in your AsyncTask. http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...)

Categories

Resources