首页 > 解决方案 > 使用服务下载文件

问题描述

要下载大量活动的一些文件,我认为将所有相同的代码集成到一个活动中会更好(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。

我听说使用服务是答案之一,但是没有办法根据我的知识更新进度条。

标签: androidserviceandroid-asynctaskdownload

解决方案


如您所知,服务在后台线程上运行,因此您没有机会更新进度条。

但是,作为替代方案,您可以使用通知部分的进度条,就像 youtube 在查看离线视频或下载任何视频时所做的那样。

另一方面,您使用一个 DownloadFiles.class 的想法非常好。那么,为什么不在活动打开并显示进度条、更新视图等时调用呢?

也不需要服务。


推荐阅读