正在下载Android下载管理器查询

时间:2017-03-03 13:52:37

标签: android download

我如何检查文件是否正在下载我有这个代码: -

   DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uri));
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            refrence = downloadManager.enqueue(request);

我需要通过“refrence”来查询下载管理器吗?

2 个答案:

答案 0 :(得分:1)

使用query()查询下载内容。当您调用enqueue()时,返回值是下载的ID。您也可以按状态查询:

Cursor c = downloadManager.query(new DownloadManager.Query()
        .setFilterByStatus(DownloadManager.STATUS_PAUSED
                | DownloadManager.STATUS_PENDING
                | DownloadManager.STATUS_RUNNING));
To be notified when a download is finished, register a BroadcastReceiver for ACTION_DOWNLOAD_COMPLETE:

BroadcastReceiver onComplete = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do something
    }
};

registerReceiver(onComplete, new IntentFilter(
        DownloadManager.ACTION_DOWNLOAD_COMPLETE));

请注意,您还应该收听ACTION_NOTIFICATION_CLICKED广播,以了解用户何时点击了正在运行下载的通知。

答案 1 :(得分:-1)

试试这段代码:

   protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;

                    // writing data to file
                    output.write(data, 0, count);
                }
                //here you can use a flag to notify the 
                //completion of download.
                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }