Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 下載功能實戰:從 Internet 保存資源到本地存儲

編輯:Android 開發教學

環境:Android 0.5.2 + Gradle 1.11 + Kindle Fire

本文實現一個下載功能:點擊 Download 按鈕從網絡下載圖片,保存到本地 SD 卡,然後可以點擊查看下載內容。

第一步:修改 activity_main.xml

位置:res → layout → activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="mzx.spike.download.app.MainActivity">

    <Button
        android:id="@+id/download_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download" />

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/download_button" />

</RelativeLayout>

添加一個 Button,並讓 TextView 位於它下方,使用的是 layout_below 屬性——這是 RelativeLayout 相對定位的典型用法。

第二步:修改 AndroidManifest.xml

位置:main → AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="mzx.spike.download.app" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="mzx.spike.download.app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

需要兩個權限:INTERNET 用於連接互聯網,WRITE_EXTERNAL_STORAGE 用於寫入存儲器。少聲明任何一個,功能都會在運行時失敗——而且 INTERNET 權限缺失的表現常常是網絡請求直接拋 UnknownHostException,讓人誤以為是 URL 寫錯了。

下載邏輯要點

佈局與權限準備好之後,核心邏輯需要注意幾點:

網絡操作必須在子線程。Android 4.0 之後主線程禁止網絡訪問,直接寫會拋 NetworkOnMainThreadException。這裡可以用 Thread、AsyncTask 或後來的 RxJava、協程,關鍵是把請求與界面更新分開,界面更新通過 Handler 拋回主線程。

動態申請存儲權限。Android 6.0(API 23)開始,WRITE_EXTERNAL_STORAGE 屬於危險權限,僅在 Manifest 中聲明是不夠的,必須在運行時調用 requestPermissions() 向用戶申請,並處理 onRequestPermissionsResult() 的授權結果。

寫文件要用緩衝流。用 BufferedInputStream 配合 FileOutputStream,並在 finally 中關閉所有流。同時考慮在 Activity 銷毀時中斷下載,避免洩露。

存儲位置要選對。寫入 Environment.getExternalStorageDirectory() 的文件對其他應用可見,適合用戶可感知的文檔;寫入 getExternalFilesDir() 返回的目錄則屬於應用私有,卸載時會被自動清理,適合緩存。此外從 Android 10 開始引入了分區存儲(Scoped Storage),直接拼接路徑寫公共目錄的方式已受限,需要改用 MediaStore API 或 SAF。

添加下載進度反饋。下載過程中根據已讀字節數更新進度條,能顯著改善用戶等待時的體驗。這也是為什麼正式項目中通常用成熟的網絡庫而非自己拼下載邏輯。

本文基於較早的 Android 版本,其中的 API 在當前版本上需要按上述說明做相應調整。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved