【问题标题】:How to check if AsyncTask has downloaded one item of a set如何检查 AsyncTask 是否已下载一组项目
【发布时间】:2015-12-30 01:26:59
【问题描述】:

我的应用是一个媒体播放器,它通过从 Internet 下载适当的文件来播放媒体。我正在使用AsyncTask 来执行此操作,但是当需要下载多个文件时执行任务需要更长的时间,这会导致媒体播放器延迟。

所需的行为是在下载文件后开始播放文件,同时继续下载任何其他文件。

我的代码如下:

public class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;
    private PowerManager.WakeLock mWakeLock;
    private String folder;
    private ProgressDialog mProgressDialog;

    private int noOfURLs;
    private int noUrlLoad;

    public DownloadTask(Context context, String folder, ProgressDialog mProgressDialog) {

        this.context = context;
        this.folder = folder;

     }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;

        try {

            noOfURLs = sUrl.length;

            for (int i = 0; i < sUrl.length; i++) {
                URL url = new URL(sUrl[i]);
                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 "Máy chủ trả về 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();
            output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + folder + "/File" + (i + 1) + "." + sUrl[i].charAt(sUrl[i].length() - 3) + sUrl[i].charAt(sUrl[i].length() - 2) + sUrl[i].charAt(sUrl[i].length() - 1));

            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));

                output.write(data, 0, count);

            }

            noUrlLoad++;

        } 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) 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);
        // if we get here, length is known, now set indeterminate to false

    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context, context.getString(R.string.error) + result, Toast.LENGTH_LONG).show();
    }

}

【问题讨论】:

标签: android file download android-asynctask


【解决方案1】:

在您的 doInBackground 方法中,调用 publishProgress(Integer) 将您的更新发送到 UI 线程。这将触发onProgressUpdate 方法被调用,您将能够看到第一次下载何时完成。

http://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2011-10-18
    • 2020-06-14
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多