2017-03-03 55 views
0

如何检查wther文件被下载或不是我有这样的代码: -Android的下载管理器查询下载

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

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

+0

更好的方法是显示进度条和下载文件。 为了达到此目的,您可以获取文件大小,然后使用公式来计算下载文件的百分比。 请点击此链接:http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/ 我希望你能为你的问题找到解决方案 – BhanuSingh

+0

我不需要显示进度条,,这应该是一个后台下载,,但耗时我只是使用下载管理器insted制作一项服务,我需要的是检查文件是否正在下载,所以用户不能点击下载,而文件正在下载或下载完成 –

+0

好的,在这种情况下,您可以选择逻辑如何计算文件下载的完成情况,请让我为您做。 – BhanuSingh

回答

1

使用查询()打听下载。当你调用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广播知道当用户点击该通知正在运行的下载。

+0

你可以做一个完整的例子,所以这可以是一个完整的答案? –

-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; 
    } 
+0

我需要使用下载管理器,它更可靠。 –