2014-01-31 121 views
25

關於android下載管理器的小問題。 這是我第一次使用它,並已成功下載多個文件並打開它們。但我的問題是我如何檢查下載是否完成。完成Android下載管理器

這種情況是我下載一個PDF文件並打開它,通常這個文件很小,它在打開之前完成。但是,如果文件有點大,在打開它之前,我該如何檢查下載管理器是否已完成下載。

我怎麼下載:

Intent intent = getIntent(); 
DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE); 
Uri Download_Uri = Uri.parse(intent.getStringExtra("Document_href")); 
DownloadManager.Request request = new DownloadManager.Request(Download_Uri); 

//Restrict the types of networks over which this download may proceed. 
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); 
//Set whether this download may proceed over a roaming connection. 
request.setAllowedOverRoaming(false); 
//Set the title of this download, to be displayed in notifications. 
request.setTitle(intent.getStringExtra("Document_title")); 
//Set the local destination for the downloaded file to a path within the application's external files directory 
request.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,intent.getStringExtra("Document_title") + ".pdf"); 
//Enqueue a new download and same the referenceId 
Long downloadReference = downloadManager.enqueue(request); 

如何打開文件

Uri uri = Uri.parse("content://com.app.applicationname/" + "/Download/" + intent.getStringExtra("Document_title") + ".pdf"); 
Intent target = new Intent(Intent.ACTION_VIEW); 
target.setDataAndType(uri, "application/pdf"); 
target.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 

startActivity(target); 

所以某處下載和打開文件之間我希望有一個if語句來檢查它是否應該繼續還是等待文件。

通過當下載完成,所以你需要註冊一個接收器,當下載完成的下載管理器發送
+1

檢查本教程的http:/ /www.gadgetsaint。com/android/download-manager/ – ASP

回答

52

廣播意圖的行動:

要註冊接收器

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

和BroadcastReciever處理器

BroadcastReceiver onComplete=new BroadcastReceiver() { 
    public void onReceive(Context ctxt, Intent intent) { 
     // your code 
    } 
}; 

您還可以創建的AsyncTask來處理大文件的下載

建立某種形式的下載對話框顯示在通知區域,比處理打開文件下載:

protected void openFile(String fileName) { 
    Intent install = new Intent(Intent.ACTION_VIEW); 
    install.setDataAndType(Uri.fromFile(new File(fileName)),"MIME-TYPE"); 
    startActivity(install); 
} 

,你也可以檢查樣本連接

Sample Code

+1

工程像一個魅力 – Msmit1993

+0

什麼對象是'registerReceiver'函數應該被調用? –

+0

嗨,我可以註冊接收器以進行下載完成以外的所有操作嗎? –

0

你不必創建文件只是爲了查看它。可以在setDataAndType()中使用COLUMN_LOCAL_URI中的URI。看下面的例子。

int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI); 
String downloadedPackageUriString = cursor.getString(uriIndex); 
Intent open = new Intent(Intent.ACTION_VIEW); 
open.setDataAndType(Uri.parse(downloadedPackageUriString), mimeType); 
open.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
startActivity(open); 
6

我花了一個多星期研究如何下載和打開文件與下載管理器和遇不到一個答案,這是對我來說完全完美的,所以這是由我來承擔的點點滴滴查找工作。我確保盡我所能記錄我的代碼。如果有任何問題,請隨時將它們留在答案下方的評論中。

此外,不要忘記將此行添加到您的AndroidManifest.xml文件!

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

我的下載管理器:

import android.app.DownloadManager; 
import android.content.ActivityNotFoundException; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.net.Uri; 
import android.os.Environment; 
import android.webkit.CookieManager; 
import android.webkit.DownloadListener; 
import android.widget.Toast; 

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class MyDownloadListener implements DownloadListener { 
    private Context mContext; 
    private DownloadManager mDownloadManager; 
    private long mDownloadedFileID; 
    private DownloadManager.Request mRequest; 

    public MyDownloadListener(Context context) { 
     mContext = context; 
     mDownloadManager = (DownloadManager) mContext 
      .getSystemService(Context.DOWNLOAD_SERVICE); 
    } 

    @Override 
    public void onDownloadStart(String url, String userAgent, String 
     contentDisposition, final String mimetype, long contentLength) { 

     // Function is called once download completes. 
     BroadcastReceiver onComplete = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       // Prevents the occasional unintentional call. I needed this. 
       if (mDownloadedFileID == -1) 
        return; 
       Intent fileIntent = new Intent(Intent.ACTION_VIEW); 

       // Grabs the Uri for the file that was downloaded. 
       Uri mostRecentDownload = 
        mDownloadManager.getUriForDownloadedFile(mDownloadedFileID); 
       // DownloadManager stores the Mime Type. Makes it really easy for us. 
       String mimeType = 
        mDownloadManager.getMimeTypeForDownloadedFile(mDownloadedFileID); 
       fileIntent.setDataAndType(mostRecentDownload, mimeType); 
       fileIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       try { 
        mContext.startActivity(fileIntent); 
       } catch (ActivityNotFoundException e) { 
        Toast.makeText(mContext, "No handler for this type of file.", 
         Toast.LENGTH_LONG).show(); 
       } 
       // Sets up the prevention of an unintentional call. I found it necessary. Maybe not for others. 
       mDownloadedFileID = -1; 
      } 
     }; 
     // Registers function to listen to the completion of the download. 
     mContext.registerReceiver(onComplete, new 
      IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 

     mRequest = new DownloadManager.Request(Uri.parse(url)); 
     // Limits the download to only over WiFi. Optional. 
     mRequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); 
     // Makes download visible in notifications while downloading, but disappears after download completes. Optional. 
     mRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); 
     mRequest.setMimeType(mimetype); 

     // If necessary for a security check. I needed it, but I don't think it's mandatory. 
     String cookie = CookieManager.getInstance().getCookie(url); 
     mRequest.addRequestHeader("Cookie", cookie); 

     // Grabs the file name from the Content-Disposition 
     String filename = null; 
     Pattern regex = Pattern.compile("(?<=filename=\").*?(?=\")"); 
     Matcher regexMatcher = regex.matcher(contentDisposition); 
     if (regexMatcher.find()) { 
      filename = regexMatcher.group(); 
     } 

     // Sets the file path to save to, including the file name. Make sure to have the WRITE_EXTERNAL_STORAGE permission!! 
     mRequest.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, filename); 
     // Sets the title of the notification and how it appears to the user in the saved directory. 
     mRequest.setTitle(filename); 

     // Adds the request to the DownloadManager queue to be executed at the next available opportunity. 
     mDownloadedFileID = mDownloadManager.enqueue(mRequest); 
    } 
} 

只需將此加入這一行到您的WebView類添加到您現有的WebView:

webView.setDownloadListener(new MyDownloadListener(webView.getContext()));

+0

它顯示錯誤401未授權 – sss

+0

當一次性文件下載正在進行中,並關閉互聯網連接,並在一段時間後啓動互聯網,而不是如何恢復下載。你有任何想法我下載使用Android的下載管理器 –