Подтвердить что ты не робот

Менеджер загрузки 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 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 проверял, следует ли продолжать или ждать файл.

4b9b3361

Ответ 1

Действие трансляции трансляции, отправленное менеджером загрузки при завершении загрузки, поэтому вам необходимо зарегистрировать приемник для завершения загрузки:

Для регистрации приемника

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

вы также можете проверить ссылку на образец

Пример кода

Ответ 2

Я потратил более недели на изучение загрузки и открытия файлов с помощью 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 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()));

Ответ 3

Вам не нужно создавать файл только для его просмотра. 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);