簡體   English   中英

Android 下載管理器進度

[英]Android DownloadManager Progress

我正在開發一個應用程序,用戶可以在其中下載不同的內容包。 對於下載過程,我使用的是 DownloadManager 類。 到目前為止工作正常。

我的問題是如何獲取使用 DownloadManager 啟動的正在運行的下載的當前進度。 我知道有內置下載通知等等。 但對我來說,我有必要獲得正在運行的下載進度,以便我可以使用它在我的應用程序的自定義進度條中顯示進度。 到目前為止,我無法檢索進度。

它甚至可能還是我只是盲目而無法找到解決方案。

希望有人可以幫助我...

我也在尋找一種更好的方法來做到這一點,但到目前為止,我計划每 1 秒左右輪詢一次進度。

DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long id = mgr.enqueue(request);

DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(id);
Cursor cursor = mgr.query(q);
cursor.moveToFirst();
int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
cursor.close();

編輯:

FileObserver可以幫助解決這個問題。 這是我整理的框架,以幫助跟蹤我們的應用程序下載了哪些文件。 在活動或服務的onStart啟動它並在onStop停止它。 結合onStart期間事物狀態的手動同步,這可以讓您對正在發生的事情有一個非常完整的了解。

特別是對於進度,觀察 OPEN/CLOSE_WRITE 事件可以幫助您決定何時開始/停止輪詢 DownloadManager 以獲取更新。

public class DownloadsObserver extends FileObserver {

    public static final String LOG_TAG = DownloadsObserver.class.getSimpleName();

    private static final int flags =
            FileObserver.CLOSE_WRITE
            | FileObserver.OPEN
            | FileObserver.MODIFY
            | FileObserver.DELETE
            | FileObserver.MOVED_FROM;
    // Received three of these after the delete event while deleting a video through a separate file manager app:
    // 01-16 15:52:27.627: D/APP(4316): DownloadsObserver: onEvent(1073741856, null)

    public DownloadsObserver(String path) {
        super(path, flags);
    }

    @Override
    public void onEvent(int event, String path) {
        Log.d(LOG_TAG, "onEvent(" + event + ", " + path + ")");

        if (path == null) {
            return;
        }

        switch (event) {
        case FileObserver.CLOSE_WRITE:
            // Download complete, or paused when wifi is disconnected. Possibly reported more than once in a row.
            // Useful for noticing when a download has been paused. For completions, register a receiver for 
            // DownloadManager.ACTION_DOWNLOAD_COMPLETE.
            break;
        case FileObserver.OPEN:
            // Called for both read and write modes.
            // Useful for noticing a download has been started or resumed.
            break;
        case FileObserver.DELETE:
        case FileObserver.MOVED_FROM:
            // These might come in handy for obvious reasons.
            break;
        case FileObserver.MODIFY:
            // Called very frequently while a download is ongoing (~1 per ms).
            // This could be used to trigger a progress update, but that should probably be done less often than this.
            break;
        }
    }
}

用法是這樣的:

public class MyActivity extends Activity {

    private FileObserver fileObserver = new DownloadsObserver(
            getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());

    @Override
    protected void onStart() {
        super.onStart();
        fileObserver.startWatching();
        syncUpDatabaseWithFileSystem();
    }

    @Override
    protected void onStop() {
        fileObserver.stopWatching();
        super.onStop();
    }
}

事實證明,Marshmallow 上的FileObserver實現有一個錯誤。 因此, FileObserver不會報告下載管理器下載的文件的任何修改。 (舊的 Android 版本沒有這個問題——它在 KitKat 上運行良好。) 來源

對我來說,以下代碼(基於此答案)運行良好。 我每秒都進行一次輪詢——我曾嘗試將該時間間隔減半,但沒有任何明顯的效果。

private static final int PROGRESS_DELAY = 1000;
Handler handler = new Handler();
private boolean isProgressCheckerRunning = false;

// when the first download starts
startProgressChecker();

// when the last download finishes or the Activity is destroyed
stopProgressChecker();

/**
 * Checks download progress.
 */
private void checkProgress() {
    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterByStatus(~(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_SUCCESSFUL));
    Cursor cursor = downloadManager.query(query);
    if (!cursor.moveToFirst()) {
        cursor.close();
        return;
    }
    do {
        long reference = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
        long progress = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
        // do whatever you need with the progress
    } while (cursor.moveToNext());
    cursor.close();
}

/**
 * Starts watching download progress.
 * 
 * This method is safe to call multiple times. Starting an already running progress checker is a no-op.
 */
private void startProgressChecker() {
    if (!isProgressCheckerRunning) {
        progressChecker.run();
    isProgressCheckerRunning = true;
    }
}

/**
 * Stops watching download progress.
 */
private void stopProgressChecker() {
    handler.removeCallbacks(progressChecker);
    isProgressCheckerRunning = false;
}

/**
 * Checks download progress and updates status, then re-schedules itself.
 */
private Runnable progressChecker = new Runnable() {
    @Override
    public void run() {
        try {
            checkProgress();
            // manager reference not found. Commenting the code for compilation
            //manager.refresh();
        } finally {
            handler.postDelayed(progressChecker, PROGRESS_DELAY);
        }
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM