我想从网址下载一些文件来刷新我的应用,但我不知道最好的方法是什么。我有这个代码下载一个文件,但是当我下载多个文件时有时会给我一个错误。是否可以在不使用Android Activity的情况下在后台进行下载?谢谢
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;
}
}
我用以下方式调用此任务:
downloadTask.execute("myurl");
答案 0 :(得分:0)
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 {
}
}
}
并将其称为whit String [] urls
new DownloadAsynkTask().execute(urls);