How to use AsyncTask to download files? [closed] - android

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm Using this class to download files:
public class DownloadService extends Service {
String downloadUrl;
LocalBroadcastManager mLocalBroadcastManager;
ProgressBar progressBar;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/org.test.download/");
double fileSize = 0;
DownloadAsyncTask dat;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public DownloadService(String url,Context c, ProgressBar pBar){
downloadUrl = url;
mLocalBroadcastManager = LocalBroadcastManager.getInstance(c);
progressBar = pBar;
dat = new DownloadAsyncTask();
dat.execute(new String[]{downloadUrl});
}
private boolean checkDirs(){
if(!dir.exists()){
return dir.mkdirs();
}
return true;
}
public void cancel(){
dat.cancel(true);
}
public class DownloadAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/")+1);
if(!checkDirs()){
return "Making directories failed!";
}
try {
URL url = new URL(downloadUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
fileSize = urlConnection.getContentLength();
FileOutputStream fos = new FileOutputStream(new File(dir,fileName));
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[500];
int bufferLength = 0;
int percentage = 0;
double downloadedSize = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
if(isCancelled()){
break;
}
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
percentage = (int) ((downloadedSize / fileSize) * 100);
publishProgress(percentage);
}
fos.close();
urlConnection.disconnect();
} catch (Exception e) {
Log.e("Download Failed",e.getMessage());
}
if(isCancelled()){
return "Download cancelled!";
}
return "Download complete";
}
#Override
protected void onProgressUpdate(Integer... values){
super.onProgressUpdate(values[0]);
if(progressBar != null){
progressBar.setProgress(values[0]);
}else{
Log.w("status", "ProgressBar is null, please supply one!");
}
}
#Override
protected void onPreExecute(){
mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_STARTED"));
}
#Override
protected void onPostExecute(String str){
mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_FINISHED"));
}
#Override
protected void onCancelled(){
mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_CANCELLED"));
}
}
}
I'm using this because apparently DownloadManager wont work prior to API 9 and i'm targeting API 7
I have ListView which parses a XML File and shows packages that can be downloaded.
How can I modify this class to accept Array of strings containing URLs and download them one by one ?
Or is there any good way to download List of files ?

Look into using an IntentService. The thread in an IntentService runs in the background, which means you don't have to handle all the mess of thread handling.
IntentService kills off its thread once its done, so you have to persist the data.
To communicate back to your Activity, use a broadcast receiver.

Related

using one ASyncTask for several times Simultaneously

I have a program with one button click, when clicked, 4 Downloads should executed Simultaneously. I use ASyncTask class for this purpose with for iterator:
for(int i=0;i<downloadCounts;i++){
new DownloadTask().execute(url[i]);
}
but in running, only one download executed and all 4 progressbars show that single download.
I want to download 4 downloads in same time. how can I do?
for more details, my download manager, get a link and divide it to 4 chunks according to file size. then with above for iterator , command it to run 4 parts download with this class:
private class DownloadChunks extends AsyncTask<Long,String,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
setStatusText(-1);
}
#Override
protected String doInBackground(Long... params) {
long s1 = params[0];
long s2 = params[1];
int count;
try{
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Range", "bytes=" + s1 + "-" + s2);
connection.connect();
len2 = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),8192);
File file = new File(Environment.getExternalStorageDirectory()+"/nuhexxxx");
if(!file.exists())file.mkdirs();
OutputStream output = new FileOutputStream(file+"/nuhe1.mp3");
byte[] data = new byte[1024];
long total = 0;
while ((count= input.read(data))!=-1){
total += count;
publishProgress(""+(int)((total*100)/len2));
output.write(data,0,count);
}
output.flush();
output.close();
input.close();
counter++;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
setStatusText(Integer.parseInt(values[0]));
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
Log.e("This part is downloaded", "..." + len2 + " start with: " + counter);
}
}
All logs shows that every thing is OK and file is completely downloaded. but each chunk download separate and in order. I want to download chunks Simultaneously
Instead of just call the .execute() method of your AsyncTask, use this logic to achieve what you want:
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
new MyAsyncTask().execute(params);
}
Check more info from the official documentation of AsyncTask

AsyncTask How to get progress from MainActivity [duplicate]

This question already has answers here:
Download a file with Android, and showing the progress in a ProgressDialog
(16 answers)
Closed 8 years ago.
Hello i am writing a download project and i'm stuck right here.
#Override
protected void onProgressUpdate(Integer... progress) {
}
//I'm using in my mainactivity like that
Download download = new Download();
download.execute("http://");
I want to get progress when updated and yeah i can do this using onProgressUpdate but i wonder about can i get it from my mainactivity i mean where i called the class. I love that kinda dynamic classes because i can use them easily my every project. Thank you btw forgive me for my grammar.
I can see two options here :
You either pass the object where you want to display the progress to your AsyncTask with the constructor and then you store it :
private ProgressObject mObject;
public void MyAsyncTask(ProgressObject object) {
mObject = object
}
And the update in the onProgress() method :
object.setProgress(); //assuming the ProgressObject has a method setProgress() obviously
Or you can set up some kind of listener :
public interface ProgressListener() {
public void onProgress(int progress);
}
private mProgressListener;
public void MyAsyncTask(ProgressListener listener) {
mProgressListener = listener;
}
then use it in the onProgress() method :
mProgressListener.onProgress(80);
Just some examples, not much but I hope that help.
Use this
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
File root = android.os.Environment.getExternalStorageDirectory();
//
File dir = new File (root.getAbsolutePath()+"/downoad"); //make ur folder to put download
if(dir.exists()==false) {
dir.mkdirs();
}
File file = new File(dir, "enter file name");
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(file);
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]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Toast.makeText(DisplayActivity.this,"Successfully downloaded in phone memory.", Toast.LENGTH_SHORT).show();
}
}
How to call?
new DownloadFileAsync().execute("your URL");

Downloading pdf from a link in Android [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to download the pdf from below URL in Android. Any idea how this can be done:
http://bkinfo.in/Murli/1305/EME-26-05-2013.pdf
Similarly, there is an mp3:
http://bkinfo.in/Murli/1305/26-05-2013.mp3
Appreciate the ideas..
Finally....
Here is the full code that I used. May be useful for someone..
Add these to manifest:
Make sure your AVD can write to SDCard(if you are writing to card). U can set it by assigning memory chunck to SDCard in AVD Manager.
public class MainActivity extends Activity {
static ProgressDialog pd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
AsyncTaskTest at = new AsyncTaskTest();
at.execute();
}
public class AsyncTaskTest extends AsyncTask<Void, Integer, Integer> {
Session s = null;
protected void onPreExecute(){
pd.show();
}
protected Integer doInBackground(Void... vd){
try{
String[] urls = new String[3];
urls[0] = "http://bkinfo.in/Murli/1305/HMS-25-05-2013.pdf";
urls[1] = "http://bkinfo.in/Murli/1305/EME-25-05-2013.pdf";
urls[2] = "http://bkinfo.in/Murli/1305/25-05-2013.mp3";
String fileName = urls[2].substring(urls[2].lastIndexOf("/")+1); //Coupying the mp3
URL url = new URL(urls[2]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(10000);
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1){
total += count;
output.write(data, 0, count);
publishProgress((int) ((total * 100) / lenghtOfFile));
}
output.flush();
output.close();
input.close();
}catch(Exception e){
Log.e("MyError:",e.toString());
}
return 0;
}
protected void onProgressUpdate(Integer... msg) {
pd.setProgress(msg[0]);
}
protected void onPostExecute(Integer in){
pd.dismiss();
showDialog("Done !");
}
private void showDialog(String msg){
final AlertDialog.Builder alertBox = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, android.R.style.Theme_Dialog));
alertBox.setMessage(msg);
alertBox.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id){
dialog.cancel();
}
}).show();
}
}
}
Hope I am not spoon feeding! I have some tough time so I decided to share my working code.
private void downloadCommandFile(String dlUrl){
int count;
try {
URL url = new URL( dlUrl );
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
int fileSize = con.getContentLength();
Log.d("TAG", "Download file size = " + fileSize );
InputStream is = url.openStream();
String dir = Environment.getExternalStorageDirectory() + "dl_directory";
File file = new File( dir );
if( !file.exists() ){
file.mkdir();
}
FileOutputStream fos = new FileOutputStream(file + "EME-26-05-2013.pdf");
byte data[] = new byte[1024];
while( (count = is.read(data)) != -1 ){
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
Log.e("TAG", "DOWNLOAD ERROR = " + e.toString() );
}
}
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String url = "http://bkinfo.in/Murli/1305/EME-26-05-2013.pdf"; // your url here
downloadCommandFile( url);
return null;
}
#Override
protected void onPostExecute(String result) {
// download complete
}
}
Call Async Task as follows:
new DownloadTask().execute();
And don't forget to add this to your manifest file:
<uses-permission android:name="android.permission.INTERNET"/>

android 2.1 AsyncTask file download not working for multiple thread work fine when call single instance

i am using android 2.1 ,api level 7 and try to implement asynchronous file download from LAN server
for this i am trying to implement AsyncTask .When i am trying to call a single thread it works find but when call multiple its just stop both the thread
/* AsyncTask class*/
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
Log.i("count","in");
URLConnection conexion = url.openConnection();
Log.i("count","in1");
conexion.connect();
Log.i("count","in2");
File root = android.os.Environment.getExternalStorageDirectory();
Log.i("count","in3");
int lenghtOfFile = conexion.getContentLength();
Log.i("count","in4");
BufferedInputStream input = new BufferedInputStream(url.openStream());
Log.i("count","in5");
OutputStream output = new FileOutputStream(root.getAbsolutePath() + "/video" +aurl[1] +".mp4");
byte data[] = new byte[1024];
long total = 0;
Log.i("count","in6");
while ((count = input.read(data)) != -1) {
//Log.i("count","in7");
total += count;
Log.i("count",aurl[1]);
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.i("progress",progress[0]);
}
#Override
protected void onPostExecute(String unused) {
Log.i("process","end");
}
}
/*main method call*/
private void startDownload() {
Log.v("count","out");
String url = lanurl+"titanic/video"+1+"_en.m4v";
new DownloadFileAsync().execute(url,"1");
url = lanurl+"titanic/video"+2+"_en.m4v";
new DownloadFileAsync().execute(url,"2");
}
output :
download both file in sd card
but no file downloading properly
I didn't understand the complete Question. But seems like your problem is with AsyncTask.
Single Object created for an AsyncTask can be used only once. If you want to use it again, you need to create an another object for the same AsyncTask.

Download in android large files

When I try this code, it starts download but then stuck with alert "force close"
what should I do? Use some kind of background thread?
try {
long startTime = System.currentTimeMillis();
URL u = new URL("http://file.podfm.ru/3/33/332/3322/mp3/24785.mp3");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File("/sdcard/","logo.mp3"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) != -1 ) {
f.write(buffer,0, len1);
}
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");
}
I was dealing with similar problem last week and ended up using AsyncTask with progress bar displayed since it could take some time for the file to be downloaded. One way of doing it is to have below class nested in your Activity and just call it where you need to simply like this:
new DownloadManager().execute("here be URL", "here be filename");
Or if the class is not located within an activity and calling from an activity..
new DownloadManager(this).execute("URL", "filename");
This passes the activity so we have access to method getSystemService();
Here is the actual code doing all the dirty work. You will probably have to modify it for your needs.
private class DownloadManager extends AsyncTask<String, Integer, Drawable>
{
private Drawable d;
private HttpURLConnection conn;
private InputStream stream; //to read
private ByteArrayOutputStream out; //to write
private Context mCtx;
private double fileSize;
private double downloaded; // number of bytes downloaded
private int status = DOWNLOADING; //status of current process
private ProgressDialog progressDialog;
private static final int MAX_BUFFER_SIZE = 1024; //1kb
private static final int DOWNLOADING = 0;
private static final int COMPLETE = 1;
public DownloadManager(Context ctx)
{
d = null;
conn = null;
fileSize = 0;
downloaded = 0;
status = DOWNLOADING;
mCtx = ctx;
}
public boolean isOnline()
{
try
{
ConnectivityManager cm = (ConnectivityManager)mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
catch (Exception e)
{
return false;
}
}
#Override
protected Drawable doInBackground(String... url)
{
try
{
String filename = url[1];
if (isOnline())
{
conn = (HttpURLConnection) new URL(url[0]).openConnection();
fileSize = conn.getContentLength();
out = new ByteArrayOutputStream((int)fileSize);
conn.connect();
stream = conn.getInputStream();
// loop with step
while (status == DOWNLOADING)
{
byte buffer[];
if (fileSize - downloaded > MAX_BUFFER_SIZE)
{
buffer = new byte[MAX_BUFFER_SIZE];
}
else
{
buffer = new byte[(int) (fileSize - downloaded)];
}
int read = stream.read(buffer);
if (read == -1)
{
publishProgress(100);
break;
}
// writing to buffer
out.write(buffer, 0, read);
downloaded += read;
// update progress bar
publishProgress((int) ((downloaded / fileSize) * 100));
} // end of while
if (status == DOWNLOADING)
{
status = COMPLETE;
}
try
{
FileOutputStream fos = new FileOutputStream(filename);
fos.write(out.toByteArray());
fos.close();
}
catch ( IOException e )
{
e.printStackTrace();
return null;
}
d = Drawable.createFromStream((InputStream) new ByteArrayInputStream(out.toByteArray()), "filename");
return d;
} // end of if isOnline
else
{
return null;
}
}
catch (Exception e)
{
e.printStackTrace();
return null;
}// end of catch
} // end of class DownloadManager()
#Override
protected void onProgressUpdate(Integer... changed)
{
progressDialog.setProgress(changed[0]);
}
#Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(/*ShowContent.this*/); // your activity
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Downloading ...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Drawable result)
{
progressDialog.dismiss();
// do something
}
}
You should try using an AsyncTask. You are getting the force quit dialog because you are trying to do too much work on the UI thread and Android judges that your application has become unresponsive.
The answers to this question have some good links.
Something like the following would be a good start:
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 doInBackground(Void... unused) {
downloadLargeFile();
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
and then execute the task with:
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading. Please Wait...");
new DownloadLargeFileTask(dialog).execute();

Categories

Resources