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

Android 6.0 下載檔案路徑怎麼設?權限機制與完整範例

編輯:關於 Android 程式設計

為什麼 6.0 之後不能「寫死」路徑

在 Android 6.0 之前,開發者只要確認外部儲存空間已經掛載,並在清單檔(AndroidManifest.xml)裡聲明對 sdcard 的讀寫權限,就能直接把檔案寫進任意子目錄。舉例來說,想把一張 a.jpg 存到 sdcard 下的「xxx」資料夾,直接把路徑寫成 /mnt/sdcard/xxx/a.jpg 就能跑起來。

但從 6.0(M)開始,Google 導入了執行期權限(Runtime Permission)機制。除了繼續在清單檔宣告權限,App 還必須在執行过程中主動向使用者提出申請,只有使用者按下「允許」之後,程式才真正取得讀寫外部儲存空間的資格。硬編碼絕對路徑的老做法,因此變得不可靠。

取得路徑的標準寫法

別再自己拼 /mnt/sdcard,改用系統提供的 API:

Environment.getExternalStorageDirectory()

它會回傳當前的外部儲存根目錄,在大多數裝置上是 /storage/emulated/0。這個目錄預設就存在,宣告權限後即可讀寫;在 6.0 及以上的系統,仍須先取得使用者的授權同意。

完整範例:下載圖片並同步更新進度條

以下程式示範如何把網路圖片下載到外部儲存空間的 HC 子目錄,並即時反映下載進度。

package com.hc.android6.download;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {

    private static final int TODOWN = 1;
    private static final String TAG = "hc";
    private static final String hcUrl = "https://p1.so.qhmsg.com/t016269623a51ead026.jpg";

    private Button button;
    private ProgressBar mprogressBar;
    private File file1;
    private int contentLength;

    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == TODOWN) {
                if (file1.length() == contentLength) {
                    Toast.makeText(getApplicationContext(), "下載完成", Toast.LENGTH_SHORT).show();
                    mprogressBar.setVisibility(View.GONE);
                } else {
                    mprogressBar.setProgress((int) file1.length());
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.download);
        mprogressBar = (ProgressBar) findViewById(R.id.progressBar);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        download();
                    }
                }).start();
            }
        });
    }

    private void download() {
        try {
            URL url = new URL(hcUrl);
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();

            contentLength = conn.getContentLength();
            mprogressBar.setMax(contentLength);
            Log.e(TAG, "contentLength = " + contentLength);

            // 以系統 API 取得外部儲存根目錄,再往下建立 HC 資料夾
            String dirName = Environment.getExternalStorageDirectory() + "/HC/";
            File dir = new File(dirName);
            if (!dir.exists()) {
                dir.mkdir();
            }

            String fileName = dirName + "hcdown.jpg";
            file1 = new File(fileName);
            if (file1.exists()) {
                file1.delete();
            }

            byte[] bs = new byte[1024];
            int len;
            OutputStream os = new FileOutputStream(fileName);
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
                mhandler.sendEmptyMessage(TODOWN);
                SystemClock.sleep(100);
            }

            Log.e(TAG, "download-finish");
            Log.e(TAG, file1.length() + "");
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

對應的 XML 版面配置只需要一個按鈕與一條進度條:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="開始下載圖片" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_below="@+id/download"
        android:layout_marginTop="10dp" />

</RelativeLayout>

重點回顧

  • 路徑一律透過 Environment.getExternalStorageDirectory() 取得,不要寫死 /mnt/sdcard。
  • 6.0 以上必須實作執行期授權流程,並處理使用者拒絕授權的情況。
  • 寫檔、讀檔屬於耗時操作,務必放在子執行緒,UI 更新透過 Handler 回到主執行緒。
  • 寫入前先檢查(必要時建立)目標目錄,避免 FileNotFoundException。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved