2014-01-31 2 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); 

Так где-то между загрузкой и открытием файла Я хочу, если заявление, чтобы проверить, если он должен продолжать или ждать файл.

+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

Hey..Can Я регистрирую приемник для всех действий, кроме Download Complete? –

0

Вам не нужны создайте файл только для его просмотра. URI в COLUMN_LOCAL_URI можно использовать в setDataAndType(). См. Пример ниже.

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

я провел в течение недели исследования, как загрузить и открывать файлы с DownloadManager и никогда не нашел ответ, который был полностью подходит для меня, так что это было до меня, чтобы взять биты и куски, чтобы найти то, что работал. Я не задумывался о том, чтобы документировать свой код в меру своих возможностей. Если есть какие-либо вопросы, пожалуйста, не стесняйтесь оставлять их в комментариях ниже ответа.

Кроме того, не забудьте добавить эту строку в свой файл 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. –