android系統(tǒng)瀏覽器下載流程

標(biāo)簽: android browser download


簡介

當(dāng)我們用瀏覽器點(diǎn)開一個(gè)下載鏈接,然后去下載,從宏觀上認(rèn)識,有下載進(jìn)度的實(shí)時(shí)更新和界面的跳轉(zhuǎn)。整個(gè)過程中,主要涉及到以下過程。瀏覽器點(diǎn)擊下載按鈕,瀏覽器分發(fā)下去一個(gè)下載請求,跳轉(zhuǎn)界面的同時(shí)在DownloadProvider進(jìn)程中去真正的下載數(shù)據(jù)以及更新數(shù)據(jù)庫,在界面上監(jiān)聽數(shù)據(jù)庫的變化,去實(shí)時(shí)更新相關(guān)進(jìn)度。全過程中,Browser進(jìn)程負(fù)責(zé)分發(fā)下載請求,DownloadProvider進(jìn)程負(fù)責(zé)真正的下載操作。

目前而言,主要有兩種結(jié)構(gòu),C-S和B-S結(jié)構(gòu)。對于Browser來說,主要在于對Webview這個(gè)控件的認(rèn)識,底層的內(nèi)核實(shí)現(xiàn)也是非常復(fù)雜,這里我們不做討論。對于一個(gè)瀏覽器鏈接,webkit底層會(huì)去解析,同時(shí)也會(huì)判斷這個(gè)鏈接屬于什么類型。比如我們今天的這個(gè)下載鏈接,Browser就有專門的下載監(jiān)聽器去回調(diào)執(zhí)行這個(gè)action,下面我們會(huì)詳細(xì)分析。

WebView控件簡單介紹

WebView控件提供了一個(gè)內(nèi)嵌的瀏覽器試圖,用于顯示本地的html或網(wǎng)路上的網(wǎng)頁。
并且比較強(qiáng)大的是,還可以直接跟js相互調(diào)用。
WebView有兩個(gè)方法:setWebChromeClient和setWebClient
WebChromeClient:主要處理解析,渲染網(wǎng)頁等瀏覽器做的事情,也是輔助WebView處理Javascript 的對話框,網(wǎng)站圖標(biāo),網(wǎng)站title,加載進(jìn)度等
WebViewClient :就是幫助WebView處理各種通知、請求事件的。

Browser下載的時(shí)序圖。

這里寫圖片描述

下面來詳細(xì)分析具體的代碼實(shí)現(xiàn)細(xì)節(jié),時(shí)序圖是更加細(xì)節(jié)的步驟,這里我們著重分析下面的流程。


Step 1:Tab.setWebView

      void setWebView(WebView w, boolean restore) {
        ....
        mMainView = w;
        // attach the WebViewClient, WebChromeClient and DownloadListener
        if (mMainView != null) {
            mMainView.setWebViewClient(mWebViewClient);
            mMainView.setWebChromeClient(mWebChromeClient);
            mMainView.setDownloadListener(mDownloadListener);
            ....
        }
    }

這個(gè)方法定義在packages/apps/Browser/src/com/android/browser/Tab.java
瀏覽器是用過Webview來顯示UI。這里設(shè)置了一個(gè)WebView對象,然后setWebViewClient和setWebChromeClient主要設(shè)置了對頁面加載以及js的處理。這里我們只分析setDownloadListener這個(gè)監(jiān)聽,首先要理解一點(diǎn),對于WebView上的一個(gè)下載按鈕,它的事件是怎么處理的,瀏覽器如何判斷這個(gè)是下載?以上其實(shí)瀏覽器內(nèi)核已經(jīng)處理,瀏覽器內(nèi)核是根據(jù)指定的url判斷該鏈接是否是一個(gè)下載鏈接,如果點(diǎn)擊的是一個(gè)下載鏈接,那么最終會(huì)回調(diào)到該監(jiān)聽器中去處理,具體底層實(shí)現(xiàn)比較復(fù)雜,暫不作討論。

 Tab(WebViewController wvcontroller, WebView w, Bundle state) {
        /// M: add for save page
        ....
        mDownloadListener = new BrowserDownloadListener() {
            public void onDownloadStart(String url, String userAgent,
                    String contentDisposition, String mimetype, String referer,
                    long contentLength) {
                /// M: add for fix download page url
                mCurrentState.mIsDownload = true;
                mWebViewController.onDownloadStart(Tab.this, url, userAgent, contentDisposition,
                        mimetype, referer, contentLength);
            }
        };
        ....
        setWebView(w);
        ....
    }

這個(gè)方法定義在packages/apps/Browser/src/com/android/browser/Tab.java
分析Tab的構(gòu)造方法,這里主要看BrowserDownloadListener這個(gè)對象。當(dāng)點(diǎn)擊了下載按鈕,則會(huì)去回調(diào)BrowserDownloadListener的onDownloadStart方法,這個(gè)最終是委托給了mWebViewController去處理。

Step 2:WebViewController.onDownloadStart

    @Override
    public void onDownloadStart(Tab tab, String url, String userAgent,
            String contentDisposition, String mimetype, String referer,
            long contentLength) {
        ....
        DownloadHandler.onDownloadStart(mActivity, url, userAgent,
                contentDisposition, mimetype, referer, false, contentLength);
        ...
    }

這個(gè)方法定義在packages/apps/Browser/src/com/android/browser/Controller.java
WebViewController是一個(gè)接口,Controller是它的具體實(shí)現(xiàn),在onDownloadStart方法中,實(shí)現(xiàn)比較簡單,直接是將參數(shù)委托給DownloadHandler的靜態(tài)方法onDownloadStart去進(jìn)一步處理。
在這里,參數(shù):
url下載的網(wǎng)址鏈接
userAgent瀏覽器userAgent信息
mimetype下載內(nèi)容的type類型
contentLength下載內(nèi)容大小

Step 3:DownloadHandler.onDownloadStart

這個(gè)方法定義在packages/apps/Browser/src/com/android/browser/DownloadHandler.java
實(shí)現(xiàn)很簡單,直接將參數(shù)繼續(xù)傳遞到onDownloadStartNoStream方法。

Step 4:DownloadHandler.onDownloadStartNoStream

    /*package */
    public static void onDownloadStartNoStream(Activity activity,
            String url, String userAgent, String contentDisposition,
            String mimetype, String referer, boolean privateBrowsing, long contentLength) {
        ....
        // java.net.URI is a lot stricter than KURL so we have to encode some
        // extra characters. Fix for b 2538060 and b 1634719
        WebAddress webAddress;
        try {
            webAddress = new WebAddress(url);
            webAddress.setPath(encodePath(webAddress.getPath()));
        } catch (Exception e) {
            // This only happens for very bad urls, we want to chatch the
            // exception here
            Log.e(LOGTAG, "Exception trying to parse url:" + url);
            return;
        }
    
        String addressString = webAddress.toString();
        Uri uri = Uri.parse(addressString);
        final DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setMimeType(mimetype);

        // let this downloaded file be scanned by MediaScanner - so that it can
        // show up in Gallery app, for example.
        request.allowScanningByMediaScanner();
        request.setDescription(webAddress.getHost());
        // XXX: Have to use the old url since the cookies were stored using the
        // old percent-encoded url.
        String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
        request.addRequestHeader("cookie", cookies);
        request.addRequestHeader("User-Agent", userAgent);
        request.addRequestHeader("Referer", referer);
        request.setNotificationVisibility(
                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setUserAgent(userAgent);
      
        final DownloadManager manager = (DownloadManager)   
                        activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("Browser download") {
                public void run() {
                    manager.enqueue(request);
                }
        }.start();
        /// M: Add to start Download activity. @{
        Intent pageView = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
        pageView.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(pageView);
        /// @}
    }

這個(gè)方法定義在packages/apps/Browser/src/com/android/browser/DownloadHandler.java
在該方法中,主要做了三件事
1.將下載信息url,minetype等封裝成一個(gè)Request對象,供后續(xù)使用。
2.獲取一個(gè)DownloadManager對象,將前面封裝的Request對象,安排到下載隊(duì)列
3.開始下載的同時(shí),去跳轉(zhuǎn)UI界面,同步顯示UI信息。
這里我們重點(diǎn)分析數(shù)據(jù)流程這塊,接下來分析enqueue這個(gè)方法的具體實(shí)現(xiàn)。

Step 5:DownloadManager.enqueue

    public long enqueue(Request request) {
        ContentValues values = request.toContentValues(mPackageName);
        Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
        if (downloadUri != null) {
            long id = Long.parseLong(downloadUri.getLastPathSegment());
            return id;
        }
        return -1;
    }

這個(gè)方法定義在frameworks/base/core/java/android/app/DownloadManager.java
首先toContentValues將Request的信息要存數(shù)據(jù)庫的字段轉(zhuǎn)化為一個(gè)ContentValues對象,以上幾步都是在Browser進(jìn)程中進(jìn)行的,接下來insert方法,通過uri開始最終跨進(jìn)程請求去插入數(shù)據(jù)。這里Downloads.Impl.CONTENT_URI為content://downloads/my_downloads,從pacakges/providers/DownloadProvider的清單文件中很容易知道最終是調(diào)用了DownloadProvider的insert方法去插入數(shù)據(jù)。
pacakges/providers/DownloadProvider的清單文件如下:

  ....
  <provider android:name=".DownloadProvider"
                  android:authorities="downloads" android:exported="true">
  ....

Step 6:DownloadProvider.insert

    @Override
    public Uri insert(final Uri uri, final ContentValues values) {
        ....
       long rowID = db.insert(DB_TABLE, null, filteredValues);
        if (rowID == -1) {
            Log.d(Constants.TAG, "couldn't insert into downloads database");
            return null;
        }
        insertRequestHeaders(db, rowID, values);
        notifyContentChanged(uri, match);
        // Always start service to handle notifications and/or scanning
        final Context context = getContext();
        context.startService(new Intent(context, DownloadService.class));
        return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, rowID);
    }

這個(gè)方法定義在packages/providers/DownloadProvider/src/com/android/providers/downloads/DownloadProvider.java
insert方法即是往DB_TABLE(downloads)表中插入了一條數(shù)據(jù)。接下來在insert方法最后啟動(dòng)DownloadService,這幾步都是在DownloadProvider進(jìn)程中進(jìn)行的。接下來會(huì)有兩條主線。
1,在DownloadProvider進(jìn)程中啟動(dòng)的這個(gè)DownloadService繼續(xù)執(zhí)行。
2,返回到Step 4 Browser進(jìn)程的中的DownloadHandler.onDownloadStartNoStream方法中去跳轉(zhuǎn)界面。
這里我們不討論UI界面,接下來分析DownloadService的操作。

Step 7:DownloadService.onCreate

   @Override
    public void onCreate() {
        super.onCreate();
        ....
        mUpdateThread = new HandlerThread(TAG + "-UpdateThread");
        mUpdateThread.start();
        mUpdateHandler = new Handler(mUpdateThread.getLooper(), mUpdateCallback);

        mScanner = new DownloadScanner(this);
        mNotifier = new DownloadNotifier(this);
        mNotifier.cancelAll();

        mObserver = new DownloadManagerContentObserver();
        getContentResolver().registerContentObserver(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
                true, mObserver);
        ....
    }

這個(gè)方法定義在packages/providers/DownloadProvider/src/com/android/providers/downloads/DownloadService.java
第一次啟動(dòng),首次執(zhí)行onCreate方法,創(chuàng)建一個(gè)HandlerThread工作線程,并注冊了一個(gè)監(jiān)聽數(shù)據(jù)庫改變的一個(gè)DownloadManagerContentObserver對象,監(jiān)聽的uri為"content://downloads/all_downloads",第2個(gè)參數(shù)為true,表示可以同時(shí)匹配其派生的Uri。接下來進(jìn)入onStartCommand方法,在onStartCommand方法中繼續(xù)執(zhí)行enqueueUpdate方法。

    public void enqueueUpdate() {
        if (mUpdateHandler != null) {
            mUpdateHandler.removeMessages(MSG_UPDATE);
            mUpdateHandler.obtainMessage(MSG_UPDATE, mLastStartId, -1).sendToTarget();
        }
    }

這個(gè)方法執(zhí)行很簡單,首先是移除掉之前所有的MSG_UPDATE消息,然后再重新發(fā)送一個(gè)MSG_UPDATE消息,接下來分析Handler這個(gè)消息的回調(diào)實(shí)現(xiàn)。

  private Handler.Callback mUpdateCallback = new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            final int startId = msg.arg1;
            final boolean isActive;
            synchronized (mDownloads) {
                isActive = updateLocked();
            }

            if (msg.what == MSG_FINAL_UPDATE) {
                mNotifier.dumpSpeeds();
            }

            if (isActive) {
                // Still doing useful work, keep service alive. These active
                // tasks will trigger another update pass when they're finished.
                // Enqueue delayed update pass to catch finished operations that
                // didn't trigger an update pass; these are bugs.
                enqueueFinalUpdate();

            } else {
                // No active tasks, and any pending update messages can be
                // ignored, since any updates important enough to initiate tasks
                // will always be delivered with a new startId.
                if (stopSelfResult(startId)) {
                    if (DEBUG_LIFECYCLE) Log.v(TAG, "Nothing left; stopped");
                    getContentResolver().unregisterContentObserver(mObserver);
                    mScanner.shutdown();
                    mUpdateThread.quit();
                }
            }
            return true;
        }
    };

這個(gè)方法處理的邏輯比較多,先整體上認(rèn)識這個(gè),主要有updateLocked方法主要負(fù)責(zé)具體的下載實(shí)現(xiàn),它的返回值是一個(gè)boolean類型,用以判斷當(dāng)前下載是否是激活狀態(tài),也就是是否有下載任務(wù)。接下來如果判斷isActive為true,則會(huì)去執(zhí)行enqueueFinalUpdate方法。

  private void enqueueFinalUpdate() {
        mUpdateHandler.removeMessages(MSG_FINAL_UPDATE);
        mUpdateHandler.sendMessageDelayed(
                mUpdateHandler.obtainMessage(MSG_FINAL_UPDATE, mLastStartId, -1),
                5 * MINUTE_IN_MILLIS);
    }

從這里我們可以看出,這個(gè)回調(diào)其實(shí)是當(dāng)有下載任務(wù)的時(shí)候,會(huì)一直的循環(huán)執(zhí)行下去,用以保證下載的任務(wù)的連續(xù)性,如果有中斷,則會(huì)重新啟動(dòng)。
下面我們來分析updateLocked的具體實(shí)現(xiàn),是如何將下載任務(wù)放入線程中去執(zhí)行的,又是怎么知道有哪些下載任務(wù)的。

Step 8 :DownloadService.updateLocked

   private boolean updateLocked() {
        ...
        final Cursor cursor = resolver.query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
                null, null, null, null);
        try {
            final DownloadInfo.Reader reader = new DownloadInfo.Reader(resolver, cursor);
            final int idColumn = cursor.getColumnIndexOrThrow(Downloads.Impl._ID);
            while (cursor.moveToNext()) {
                final long id = cursor.getLong(idColumn);
                staleIds.remove(id);
                DownloadInfo info = mDownloads.get(id);
                if (info != null) {
                    updateDownload(reader, info, now);
                } else {
                    info = insertDownloadLocked(reader, now);
                }
                if (info.mDeleted) {
                    // Delete download if requested, but only after cleaning up
                    if (!TextUtils.isEmpty(info.mMediaProviderUri)) {
                        resolver.delete(Uri.parse(info.mMediaProviderUri), null, null);
                    }
                    deleteFileIfExists(info.mFileName);
                    resolver.delete(info.getAllDownloadsUri(), null, null);
                } else {
                    // Kick off download task if ready
                    final boolean activeDownload = info.startDownloadIfReady(mExecutor);
                    // Kick off media scan if completed
                    final boolean activeScan = info.startScanIfReady(mScanner);
                    isActive |= activeDownload;
                    isActive |= activeScan;
                }

                // Keep track of nearest next action
                nextActionMillis = Math.min(info.nextActionMillis(now), nextActionMillis);
            }
        } finally {
            cursor.close();
        }
        // Clean up stale downloads that disappeared
        for (Long id : staleIds) {
            deleteDownloadLocked(id);
        }
        ...
        return isActive;
    }

這個(gè)方法的實(shí)現(xiàn)分為幾步:
1.查詢downloads表中的所有記錄,接著將其封裝成一個(gè)DownloadInfo對象。
2.顯然第一次DownloadInfo的info是空值,接下來insertDownloadLocked會(huì)根據(jù)Cursor去新建一個(gè)DownloadInfo信息。
3.DownloadInfo緩存的管理,將DownloadInfo緩存至mDownloads中管理。這里有個(gè)小的判斷分支,如果info.mDeleted為true,則刪除掉這條下載記錄,并且對應(yīng)的文件也將被刪除,其實(shí)屬于邏輯控制,跟下載無太大關(guān)系,不用太糾結(jié)。
4.對于一個(gè)新的下載,info.mDeleted顯然是false,所以會(huì)進(jìn)入到到else語句,調(diào)用DownloadInfo的startDownloadIfReady方法開始下載。
我們先分析insertDownloadLocked新建一個(gè)下載任務(wù)DownloadInfo的流程

    private DownloadInfo insertDownloadLocked(DownloadInfo.Reader reader, long now) {
        final DownloadInfo info = reader.newDownloadInfo(this, mSystemFacade, mNotifier);
        mDownloads.put(info.mId, info);

        if (Constants.LOGVV) {
            Log.v(Constants.TAG, "processing inserted download " + info.mId);
        }

        return info;
    }

這個(gè)方法中,調(diào)用DownloadInfo.Reader去新建一個(gè)下載任務(wù),從前面可以看出,這個(gè)reader對象是由數(shù)據(jù)庫Cursor進(jìn)行封裝的,具體分析reader.newDownloadInfo方法

       public DownloadInfo newDownloadInfo(
                Context context, SystemFacade systemFacade, DownloadNotifier notifier) 
            final DownloadInfo info = new DownloadInfo(context, systemFacade, notifier);
            updateFromDatabase(info);
            readRequestHeaders(info);
            return info;
        }

這個(gè)方法定義在packages/providers/DownloadProvider/src/com/android/providers/downloads/DownloadInfo.java
Reader是DownloadInfo的一個(gè)靜態(tài)內(nèi)部類,這個(gè)方法中,首先是new了一個(gè)DownloadInfo對象,然后調(diào)用updateFromDatabase去更新DownloadInfo的一些屬性值。實(shí)現(xiàn)比較簡單,就是根據(jù)前面的Cursor對象,獲取數(shù)據(jù)庫的一些字段值保存在DownloadInfo中。

從這里我們可以看出,數(shù)據(jù)庫中所有的信息都會(huì)封裝成一個(gè)下載DownloadInfo,那么它是通過什么來判斷當(dāng)前數(shù)據(jù)是否是需要下載的任務(wù)呢?顯然如果這個(gè)url對應(yīng)的任務(wù)已經(jīng)被下載完成了,那么肯定是不需要再次下載的。接下來我們繼續(xù)往下走,進(jìn)入到startDownloadIfReady這個(gè)方法。

Step 9:DownloadInfo.startDownloadIfReady

public boolean .startDownloadIfReady(ExecutorService executor) {
        synchroized (this) {
            final boolean isReady = isReadyToDownload();
            final boolean isActive = mSubmittedTask != null && !mSubmittedTask.isDone();
            if (isReady && !isActive) {
                if (mStatus != Impl.STATUS_RUNNING) {
                    mStatus = Impl.STATUS_RUNNING;
                    ContentValues values = new ContentValues();
                    values.put(Impl.COLUMN_STATUS, mStatus);
                    mContext.getContentResolver().update(getAllDownloadsUri(), values, null, null);
                }
                mTask = new DownloadThread(mContext, mSystemFacade, mNotifier, this);
                mSubmittedTask = executor.submit(mTask);
            }
            return isReady;
        }
    }

這個(gè)方法定義在packages/providers/DownloadProvider/src/com/android/providers/downloads/DownloadInfo.java
我們先分析isReadyToDownload這個(gè)方法。

   private boolean isReadyToDownload() {
        ....
        switch (mStatus) {
            case 0: // status hasn't been initialized yet, this is a new download
            case Downloads.Impl.STATUS_PENDING: // download is explicit marked as ready to start
            case Downloads.Impl.STATUS_RUNNING: // download interrupted (process killed etc) while
                                                // running, without a chance to update the database
                return true;

            case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
            case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
                return checkCanUseNetwork(mTotalBytes) == NetworkState.OK;

            case Downloads.Impl.STATUS_WAITING_TO_RETRY:
                // download was waiting for a delayed restart
                final long now = mSystemFacade.currentTimeMillis();
                return restartTime(now) <= now;
            case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
                // is the media mounted?
                return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
            /// M: Because OMA DL spec, if insufficient memory, we
            /// will show to user but not retry.
            //case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
                // should check space to make sure it is worth retrying the download.
                // but thats the first thing done by the thread when it retries to download
                // it will fail pretty quickly if there is no space.
                // so, it is not that bad to skip checking space availability here.
                //return true;
            /// M: Add for fix alp00406729, file already exist but user do not operation. @{
            case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
                return false;
            /// @}
        }
        return false;
    }

一切都明白了,這里就是根據(jù)mStatus這個(gè)字段,來判斷這個(gè)任務(wù)是否需要下載,也解決了我們之前的疑問,返回值為true的才會(huì)去執(zhí)行下載,我們可以回頭看看Browser里面當(dāng)時(shí)insert一條下載記錄的時(shí)候,是沒有插入mStatus這個(gè)字段的,所以對于一個(gè)新任務(wù)這里mStatus為默認(rèn)值即0,整個(gè)返回值為true。
接下來分析isActive這個(gè)boolean值,它主要用來標(biāo)識當(dāng)前DownloadInfo是否在線程中去執(zhí)行了,保證一個(gè)DownloadInfo只執(zhí)行一次,對于新任務(wù),顯然初始化的時(shí)候mSubmittedTask為null。

接下來進(jìn)入if語句,先update數(shù)據(jù)庫中的COLUMN_STATUS字段置為STATUS_RUNNING。然后新建一個(gè)DownloadThread,放入到ExecutorService線程池中去執(zhí)行,這樣一個(gè)下載鏈接就正式開始下載了。接下來分析下載讀寫文件以及更新數(shù)據(jù)庫的動(dòng)作。

Step 10:new DownloadThread

  @Override
    public void run() {
        ....
        if (DownloadInfo.queryDownloadStatus(mContext.getContentResolver(), mId)
                == Downloads.Impl.STATUS_SUCCESS) {
            logDebug("Already finished; skipping");
            return;
        }
        ....
        executeDownload();
        ....
    }

這個(gè)方法定義在
DownloadThread是一個(gè)Runnable對象,這里我們關(guān)注構(gòu)造方法中的第4個(gè)參數(shù),即DownloadInfo,將DownloadInfo這個(gè)對象的信息,傳給DownloadThread的成員變量,還有DownloadInfoDelta對象,最后用于更新下載進(jìn)度數(shù)據(jù)庫信息,我們后續(xù)分析。這樣就完全得到了這條下載信息的內(nèi)容。接下來去執(zhí)行DownloadThread的run方法,在新的線程中進(jìn)行下載。在run方法的實(shí)現(xiàn)中,首先是再次確認(rèn)這個(gè)任務(wù)是需要下載的,否則直接return,線程結(jié)束,然后如果需要下載則去調(diào)用executeDownload方法去執(zhí)行。

  private void executeDownload() throws StopRequestException {
        .....
        URL url;
        try {
            // TODO: migrate URL sanity checking into client side of API
            url = new URL(mInfoDelta.mUri);
        } catch (MalformedURLException e) {
            throw new StopRequestException(STATUS_BAD_REQUEST, e);
        }

        int redirectionCount = 0;
        while (redirectionCount++ < Constants.MAX_REDIRECTS) {
            // Open connection and follow any redirects until we have a useful
            // response with body.
            HttpURLConnection conn = null;
            try {
                checkConnectivity();
                conn = (HttpURLConnection) url.openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setConnectTimeout(DEFAULT_TIMEOUT);
                conn.setReadTimeout(DEFAULT_TIMEOUT);

                addRequestHeaders(conn, resuming);

                final int responseCode = conn.getResponseCode();
                switch (responseCode) {
                    case HTTP_OK:
                        ....
                        /// @}
                        transferData(conn);
                        return;

             .....
        }

        throw new StopRequestException(STATUS_TOO_MANY_REDIRECTS, "Too many redirects");
    }

在executeDownload方法中根據(jù)url創(chuàng)建一個(gè)HttpURLConnection連接。然后判斷getResponseCode網(wǎng)絡(luò)端返回值。這里我們分析HTTP_OK的情況。在HTTP_OK:接下來調(diào)用transferData(conn);傳入的參數(shù)為這個(gè)HttpURLConnection這個(gè)連接。

Step 11:DownloadThread.transferData

   private void transferData(HttpURLConnection conn) throws StopRequestException {
        ....
        DrmManagerClient drmClient = null;
        ParcelFileDescriptor outPfd = null;
        FileDescriptor outFd = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            try {
                in = conn.getInputStream();
            } catch (IOException e) {
                throw new StopRequestException(STATUS_HTTP_DATA_ERROR, e);
            }
            try {
                outPfd = mContext.getContentResolver()
                        .openFileDescriptor(mInfo.getAllDownloadsUri(), "rw");
                outFd = outPfd.getFileDescriptor();

                if (DownloadDrmHelper.isDrmConvertNeeded(mInfoDelta.mMimeType)) {
                    drmClient = new DrmManagerClient(mContext);
                    out = new DrmOutputStream(drmClient, outPfd, mInfoDelta.mMimeType);
                } else {
                    out = new ParcelFileDescriptor.AutoCloseOutputStream(outPfd);
                }

                // Pre-flight disk space requirements, when known
                if (mInfoDelta.mTotalBytes > 0) {
                    final long curSize = Os.fstat(outFd).st_size;
                    final long newBytes = mInfoDelta.mTotalBytes - curSize;
                    StorageUtils.ensureAvailableSpace(mContext, outFd, newBytes);
                    // We found enough space, so claim it for ourselves
                    Os.posix_fallocate(outFd, 0, mInfoDelta.mTotalBytes);
                }
                // Move into place to begin writing
                Os.lseek(outFd, mInfoDelta.mCurrentBytes, OsConstants.SEEK_SET);

            } catch (ErrnoException e) {
                throw new StopRequestException(STATUS_FILE_ERROR, e);
            } catch (IOException e) {
                throw new StopRequestException(STATUS_FILE_ERROR, e);
            }
            // Start streaming data, periodically watch for pause/cancel
            // commands and checking disk space as needed.
            transferData(in, out, outFd);
            ....
    }

這個(gè)方法定義在packages/providers/DownloadProvider/src/com/android/providers/downloads/DownloadThread.java
在這個(gè)方法中,獲取一個(gè)該url對應(yīng)的網(wǎng)絡(luò)輸入流對象InputStream,同時(shí)根據(jù)uri構(gòu)造一個(gè)文件描述符,進(jìn)而構(gòu)建一個(gè)輸出流OutputStream對象,最后到重載的transferData方法,將輸入輸出流,以及文件描述符傳入transferData開始存儲文件。

  private void transferData(InputStream in, OutputStream out, FileDescriptor outFd)
            throws StopRequestException {
        final byte buffer[] = new byte[Constants.BUFFER_SIZE];
        while (true) {
            checkPausedOrCanceled();
            int len = -1;
            try {
                len = in.read(buffer);
            } catch (IOException e) {
                throw new StopRequestException(
                        STATUS_HTTP_DATA_ERROR, "Failed reading response: " + e, e);
            }
            if (len == -1) {
                break;
            }
            try {
                // When streaming, ensure space before each write
                if (mInfoDelta.mTotalBytes == -1) {
                    final long curSize = Os.fstat(outFd).st_size;
                    final long newBytes = (mInfoDelta.mCurrentBytes + len) - curSize;
                    StorageUtils.ensureAvailableSpace(mContext, outFd, newBytes);
                }
                out.write(buffer, 0, len);
                mMadeProgress = true;
                mInfoDelta.mCurrentBytes += len;
                updateProgress(outFd);
            } catch (ErrnoException e) {
                throw new StopRequestException(STATUS_FILE_ERROR, e);
            } catch (IOException e) {
                throw new StopRequestException(STATUS_FILE_ERROR, e);
            }
        }
       .....
    }

真正開始下載都是在這段code中,首先checkPausedOrCanceled方法檢查是否有取消下載請求,如果有直接進(jìn)入catch語句跳過,下載結(jié)束。如果沒有取消,則執(zhí)行while語句,執(zhí)行輸入輸出流的讀寫操作。每一次讀寫的同時(shí)都會(huì)執(zhí)行updateProgress方法,顯然該方法是用來更新進(jìn)度的,下面具體來分析。

Step 12:DownloadThread.updateProgress

    private void updateProgress(FileDescriptor outFd) throws IOException, StopRequestException {
     ....
        final long bytesDelta = currentBytes - mLastUpdateBytes;
        final long timeDelta = now - mLastUpdateTime;
        if (bytesDelta > Constants.MIN_PROGRESS_STEP && timeDelta > Constants.MIN_PROGRESS_TIME) {
            // fsync() to ensure that current progress has been flushed to disk,
            // so we can always resume based on latest database information.
            outFd.sync();
            //mInfoDelta.writeToDatabaseOrThrow();
            mInfoDelta.writeToDatabaseWithoutModifyTime();
            mLastUpdateBytes = currentBytes;
            mLastUpdateTime = now;
        }
    }

這個(gè)方法定義在packages/providers/DownloadProvider/src/com/android/providers/downloads/DownloadThread.java
總共做了兩件事,第一,調(diào)用outFd.sync強(qiáng)制所有系統(tǒng)緩沖區(qū)與基礎(chǔ)設(shè)備同步,第二調(diào)用mInfoDelta的writeToDatabaseWithoutModifyTime去更新數(shù)據(jù)庫操作,即將當(dāng)前進(jìn)度,下載了多少update到數(shù)據(jù)庫。

Step 13:DownloadInfoDelta.writeToDatabaseWithoutModifyTime

    public void writeToDatabaseWithoutModifyTime() throws StopRequestException {
            final ContentValues values = new ContentValues();

            values.put(Downloads.Impl.COLUMN_URI, mUri);
            values.put(Downloads.Impl._DATA, mFileName);
            values.put(Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
            values.put(Downloads.Impl.COLUMN_STATUS, mStatus);
            values.put(Downloads.Impl.COLUMN_FAILED_CONNECTIONS, mNumFailed);
            values.put(Constants.RETRY_AFTER_X_REDIRECT_COUNT, mRetryAfter);
            values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, mTotalBytes);
            values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, mCurrentBytes);
            values.put(Constants.ETAG, mETag);

            values.put(Downloads.Impl.COLUMN_ERROR_MSG, mErrorMsg);

            if (mContext.getContentResolver().update(mInfo.getAllDownloadsUri(),
                    values, Downloads.Impl.COLUMN_DELETED + " == '0'", null) == 0) {
                throw new StopRequestException(STATUS_CANCELED, "Download deleted or missing!");
            }
        }
     
    }

這個(gè)方法定義在packages/providers/DownloadProvider/src/com/android/providers/downloads/DownloadThread.java
DownloadInfoDelta是DownloadThread的一個(gè)內(nèi)部類,主要用于更新數(shù)據(jù)庫進(jìn)度操作,這個(gè)方法中此時(shí)uri為"content://downloads/all_downloads/id",對應(yīng)DownloadProvider的update方法去更新數(shù)據(jù)庫,而此時(shí)又會(huì)回調(diào)至DowbloadService中的DownloadManagerContentObserver監(jiān)聽中,因?yàn)榇藭r(shí)對應(yīng)uri數(shù)據(jù)庫內(nèi)容已經(jīng)改變。至此,整個(gè)updateLocked方法執(zhí)行完畢。

簡單分析DownloadManagerContentObserver內(nèi)容,可以看出這個(gè)目的還是保證了下載的連續(xù)性,只要每次有下載數(shù)據(jù)更新,則會(huì)循環(huán)檢測,以確保下載任務(wù)的連續(xù)性。

 private class DownloadManagerContentObserver extends ContentObserver {
        public DownloadManagerContentObserver() {
            super(new Handler());
        }

        @Override
        public void onChange(final boolean selfChange) {
            enqueueUpdate();
        }
    }

至此,整個(gè)下載過程已經(jīng)結(jié)束,至于UI界面的更新情況,則只需要監(jiān)聽數(shù)據(jù)庫中的數(shù)據(jù)變化,或者在有下載任務(wù)時(shí)候,間隔一段時(shí)間去數(shù)據(jù)庫查詢進(jìn)度信息,更新進(jìn)度即可。

對于下載界面,自4.4之后,都是BrowserActivity->DownloadList->DocumentActivity,而且對于DocumentUI正是采用的一段時(shí)間查詢數(shù)據(jù)庫,更新的方式,這里我們也不討論了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容