Try this just pass your url
class DownloadTask(private val context: Context) : AsyncTask<String, Int,
String(){
private var mWakeLock: PowerManager.WakeLock? = null
override fun doInBackground(vararg params: String?): String? {
var input: InputStream? = null
val output: OutputStream? = null
var connection: HttpURLConnection? = null
try {
val url = URL(params.get(0))
connection = url.openConnection() as HttpURLConnection
connection.connect()
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.responseCode != HttpURLConnection.HTTP_OK) {
return ("Server returned HTTP " + connection.responseCode
+ " " + connection.responseMessage)
}
// this will be useful to display download percentage
// might be -1: server did not report the length
val fileLength = connection.contentLength
// download the file
input = connection.inputStream
val appName = params[0]!!.split("/".toRegex()).toTypedArray()
val output = FileOutputStream(context.getExternalFilesDir(null).toString()
+ File.separator + appName[appName.size - 1])
// output = FileOutputStream("/sdcard/file_name.extension")
val data = ByteArray(4096)
var total: Long = 0
var count: Int
while (input.read(data).also { count = it } != -1) {
// allow canceling with back button
if (isCancelled) {
input.close()
return null
}
total += count.toLong()
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((total * 100 / fileLength).toInt())
output.write(data, 0, count)
}
} catch (e: Exception) {
return e.toString()
} finally {
try {
output?.close()
input?.close()
} catch (ignored: IOException) {
}
connection?.disconnect();
}
return null
}
override fun onPreExecute() {
super.onPreExecute()
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
javaClass.name)
mWakeLock!!.acquire(5 * 60 * 1000L /*10 minutes*/)
mProgressBar!!.visibility = View.VISIBLE
}
override fun onProgressUpdate(vararg progress: Int?) {
super.onProgressUpdate(*progress)
mProgressBar!!.isIndeterminate = false
mProgressBar!!.max = 100
mProgressBar!!.progress = progress[0]!!
mProgressTextView!!.text = getString(R.string.progress, progress[0].toString()) //progress[0].toString() + "/100"
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
mWakeLock!!.release()
if (result != null) {
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
}
I have modified `AsyncTask` class to handle creation of `progressDialog` at the same context .I think following code will be more reusable.
(it can be called from any activity just pass context,target File,dialog message)
public static class DownloadTask extends AsyncTask<String, Integer, String> {
private ProgressDialog mPDialog;
private Context mContext;
private PowerManager.WakeLock mWakeLock;
private File mTargetFile;
//Constructor parameters :
// @context (current Activity)
// @targetFile (File object to write,it will be overwritten if exist)
// @dialogMessage (message of the ProgresDialog)
public DownloadTask(Context context,File targetFile,String dialogMessage) {
this.mContext = context;
this.mTargetFile = targetFile;
mPDialog = new ProgressDialog(context);
mPDialog.setMessage(dialogMessage);
mPDialog.setIndeterminate(true);
mPDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mPDialog.setCancelable(true);
// reference to instance to use inside listener
final DownloadTask me = this;
mPDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
me.cancel(true);
}
});
Log.i("DownloadTask","Constructor done");
}
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = 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();
}
Log.i("DownloadTask","Response " + connection.getResponseCode());
// 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(mTargetFile,false);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
Log.i("DownloadTask","Cancelled");
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;
}
@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) mContext.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mPDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mPDialog.setIndeterminate(false);
mPDialog.setMax(100);
mPDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
Log.i("DownloadTask", "Work Done! PostExecute");
mWakeLock.release();
mPDialog.dismiss();
if (result != null)
Toast.makeText(mContext,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(mContext,"File Downloaded", Toast.LENGTH_SHORT).show();
}
}