AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params
, Progress
and Result
, and 4 steps, called onPreExecute
, doInBackground
, onProgressUpdate
and onPostExecute
.
you able to download any type of file that you want. just pass your download file url. this AsyncTask class is complete reusable.
******Activity Class*************
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Download(MyActivity.this,”Your Download File Url”).execute();
}
}
********AsyncTask Class********
public class Download extends AsyncTask<Void, Void, String> {
ProgressDialog mProgressDialog;
Context context;
String url
public Download(Context context,String url) {
this.context = context;
this.url=url;
}
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, “”,
“Please wait, Download …”);
}
protected String doInBackground(Void… params) {
// //////////////////////
try {
URL url = new URL(url);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod(“GET”);
c.setDoOutput(true);
c.connect();
String[] path = url.getPath().split(“/”);
String mp3 = path[path.length – 1];
int lengthOfFile = c.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ “/DownLoad/” ;
Log.v(“”, “PATH: ” + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = mp3;
File outputFile = new File(file , fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return “done”;
}
protected void onPostExecute(String result) {
if (result.equals(“done”)) {
mProgressDialog.dismiss();
}
}
}