要下载许多活动的一些文件,我认为将所有相同的代码集成到一个活动中会更好(DownloadFiles.class),但问题在于。我必须在我的主要活动 (SetupActivity.class) 中获取进度值,使用 AsyncTask 是不可能做到的。原来的代码是:
private class DownloadFiles extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadFiles(Context context) {
this.context = context;
}
@Override
protected String doInBackground(String... input_value) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(input_value[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(new File(input_value[1]));
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
total += count;
if (fileLength > 0)
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){
ignored.printStackTrace();
}
return "Download Complete.";
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(String result) {
mWakeLock.release();
if (!result.equals("Download Complete.")) {
} else {
}
}
}
它无法使用 onProgressUpdate 来处理其他活动的进度条。我不使用ProgressDialog的原因是因为它已被弃用,最好使用不会阻止用户与用户界面交互的 Progressbar。
我听说使用服务是答案之一,但没有办法根据我的知识更新进度条。
您还可以将回调值传递给 AsyncTask,如下所示:
private class DownloadFiles extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
private ProgressCallback mProgressCallback
public DownloadFiles(Context context, ProgressCallback callback) {
this.context = context;
mProgressCallback = callback
}
然后你创建一个这样的界面:
public interface ProgressCallback{
void onProgressUpdate(int percentComplete);
让每个需要显示进度的活动或片段实现此接口,然后您可以从 asyncTask 中的 onProgressupdate 调用:
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressCallback.onProgressUpdate(progress[0])
}
您可以随心所欲地调整界面和方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句