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

Android 四大元件之 ContentProvider(下):深入 SAF 儲存存取架構

編輯:關於 Android 程式設計

讀完上一篇,你應該已經能熟練使用系統提供的 ContentProvider,也能自己動手寫一個。但官方文件裡其實還藏著幾個現成的 Provider,值得認識一下:

  • Calendar Provider:日曆資源庫,透過它提供的 API 可以對日曆、時間、行程、提醒等資料做增刪改查。
  • Contacts Provider:聯絡人資源庫,是實務上最常被用到的那一個。
  • Storage Access Framework(SAF):Android 4.4 才加入的檔案存取框架,也是本文的主角。

一、SAF 是什麼

在 4.4 之前,想讓使用者挑一張圖片,多半得靠 Intent 加上各種 MIME type 硬湊,不同機器的行為還未必一致。4.4 帶來的 Storage Access Framework 把這件事標準化了:系統內建一個統一的檔案挑選器(DocumentsUI),你只要發出一個 Intent,它就會列出所有可用的檔案來源。

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivity(intent);

二、SAF 的組成

SAF 由三個角色構成:

  • Document Provider:一種特殊的 ContentProvider,讓某個儲存服務(例如 Google Drive)能把自己管理的檔案對外展示。它繼承自 DocumentsProvider,內部一樣以傳統的目錄樹形式組織資料,至於底層怎麼存則完全自便。Android 系統本身已內建下載、圖片、影片等幾個 Provider。
  • Client App:普通應用程式,觸發 ACTION_OPEN_DOCUMENT 或 ACTION_CREATE_DOCUMENT,就能收到 Provider 回傳的內容與 Uri。
  • Picker:系統級的檔案挑選介面,也就是 DocumentsUI。它是呼叫方與各個 Provider 之間的橋樑,負責列出符合條件的內容並讓使用者挑選。

SAF 帶來幾個實用特性:使用者可以瀏覽所有 Provider 提供的內容,而不受限於單一 App;取得授權後能長期持續存取該檔案,權限會持久化;可以新增、刪除、編輯、儲存 Provider 所維護的內容;支援多使用者與臨時性服務,例如 USB 儲存裝置只有在插入後才會出現。

核心概念上,SAF 的實作重點就是繼承 DocumentsProvider —— 它本質上仍是一個 ContentProvider,只是對外以檔案層級結構呈現。底層怎麼組織資料,由你自己決定,只要能透過 DocumentsProvider 的 API 讀取即可。

三、整體流程

下圖展示一個相簿 App 使用 SAF 時可能的結構:

Picker 是連接呼叫方與內容提供者的樞紐。當 App 送出 ACTION_OPEN_DOCUMENT 或 ACTION_CREATE_DOCUMENT,Picker 便會開啟,列出所有可用的 Document Provider(如 DriveDocProvider、UsbDocProvider、CloudDocProvider)。Intent 中還可以加上過濾條件,例如把 MIME type 限制為 image。

如果你另外裝了看图軟體並註冊了對應的 Provider,也會一併出現在清單裡。整體流程就是:送出 Intent → Picker 開啟 → 使用者挑選 → 取得檔案相關資訊。

四、客戶端取得 Uri

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int READ_REQUEST_CODE = 42;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_show = (Button) findViewById(R.id.btn_show);
        btn_show.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(intent, READ_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                Log.e("HeHe", "Uri: " + uri.toString());
            }
        }
    }
}

Picker 關閉後,Logcat 中可看到類似 content://com.android.providers.media.documents/document/image%3A69983 的 Uri。

五、從 Uri 取得檔案資訊

拿到 Uri 之後,就可以透過 ContentResolver 查詢檔案名稱與大小:

public void dumpImageMetaData(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null, null);
    try {
        if (cursor != null && cursor.moveToFirst()) {
            String displayName = cursor.getString(
                    cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            Log.e("HeHe", "Display Name: " + displayName);

            int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
            String size = null;
            if (!cursor.isNull(sizeIndex)) {
                size = cursor.getString(sizeIndex);
            } else {
                size = "Unknown";
            }
            Log.e("HeHe", "Size: " + size);
        }
    } finally {
        cursor.close();
    }
}

輸出會是檔案名稱與以 byte 為單位的大小。

六、把 Uri 轉成 Bitmap

private Bitmap getBitmapFromUri(Uri uri) throws IOException {
    ParcelFileDescriptor parcelFileDescriptor =
            getContentResolver().openFileDescriptor(uri, "r");
    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
    Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
    parcelFileDescriptor.close();
    return image;
}

七、把 Uri 轉成輸入流

private String readTextFromUri(Uri uri) throws IOException {
    InputStream inputStream = getContentResolver().openInputStream(uri);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
    }
    reader.close();
    inputStream.close();
    return stringBuilder.toString();
}

也就是說,Uri 一旦到手,檔案名稱、大小、點陣圖、文字內容都能取回;而 Uri 本身則是由 SAF 負責取得。

八、建立與刪除檔案

建立新檔案:

private void createFile(String mimeType, String fileName) {
    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType(mimeType);
    intent.putExtra(Intent.EXTRA_TITLE, fileName);
    startActivityForResult(intent, WRITE_REQUEST_CODE);
}

一樣在 onActivityResult() 中取得新建檔案的 Uri。刪除檔案則需確認 Document.COLUMN_FLAGS 含有 SUPPORTS_DELETE:

DocumentsContract.deleteDocument(getContentResolver(), uri);

九、自實作一個 Document Provider

如果你希望自家 App 的資料也能在 DocumentsUI 中被瀏覽,就得自己寫一個 provider。註冊步驟如下:

  • API 版本需為 19 或以上;
  • 在 manifest.xml 中註冊該 Provider;
  • name 為類名加包名,例如 com.example.android.storageprovider.MyCloudProvider;
  • authorities 為包名加 provider 類型名,例如 com.example.android.storageprovider.documents;
  • android:exported 設為 true。
<manifest ...>
    ...
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="19" />
    ...
    <provider
        android:authorities="com.example.android.storageprovider.documents"
        android:enabled="@bool/atLeastKitKat"
        android:exported="true"
        android:grantUriPermissions="true"
        android:name="com.example.android.storageprovider.MyCloudProvider"
        android:permission="android.permission.MANAGE_DOCUMENTS">
        <intent-filter>
        </intent-filter>
    </provider>
</manifest>

DocumentsProvider 的子類至少要實作四個方法:

queryRoots()
queryChildDocuments()
queryDocument()
openDocument()

其餘方法都是選填。以下示範一個走檔案系統的簡易寫法。

實作 queryRoots:

@Override
public Cursor queryRoots(String[] projection) throws FileNotFoundException {
    // 使用呼叫方要求的欄位,若為 null 則退回預設投影
    final MatrixCursor result = new MatrixCursor(resolveRootProjection(projection));

    // 使用者未登入時回傳空 cursor,等於把本 provider 從清單中隱藏
    if (!isUserLoggedIn()) {
        return result;
    }

    // 一個 App 可以提供多個 root(例如多帳號),此處只建立一個名為 "MyCloud" 的 root
    final MatrixCursor.RowBuilder row = result.newRow();
    row.add(Root.COLUMN_ROOT_ID, ROOT);
    row.add(Root.COLUMN_SUMMARY, getContext().getString(R.string.root_summary));

    // FLAG_SUPPORTS_CREATE:root 底下至少有目錄可建立文件
    // FLAG_SUPPORTS_RECENTS:最近使用的文件會出現在「最近」分類
    // FLAG_SUPPORTS_SEARCH:允許使用者搜尋本 App 分享的所有文件
    row.add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE
            | Root.FLAG_SUPPORTS_RECENTS
            | Root.FLAG_SUPPORTS_SEARCH);

    // root 的標題,例如 Gallery、Drive
    row.add(Root.COLUMN_TITLE, getContext().getString(R.string.title));

    // 文件 id 一旦分享出去就不能再改變
    row.add(Root.COLUMN_DOCUMENT_ID, getDocIdForFile(mBaseDir));

    // 子節點的 MIME 類型,用於篩選 root
    row.add(Root.COLUMN_MIME_TYPES, getChildMimeTypes(mBaseDir));
    row.add(Root.COLUMN_AVAILABLE_BYTES, mBaseDir.getFreeSpace());
    row.add(Root.COLUMN_ICON, R.drawable.ic_launcher);
    return result;
}

實作 queryChildDocuments:

public Cursor queryChildDocuments(String parentDocumentId, String[] projection,
        String sortOrder) throws FileNotFoundException {
    final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
    final File parent = getFileForDocId(parentDocumentId);
    for (File file : parent.listFiles()) {
        // 補上顯示名稱、MIME 類型、大小等欄位
        includeFile(result, null, file);
    }
    return result;
}

實作 queryDocument:

@Override
public Cursor queryDocument(String documentId, String[] projection)
        throws FileNotFoundException {
    final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
    includeFile(result, documentId, null);
    return result;
}

十、4.4 以上版本取得真實路徑

SAF 實務上最常被拿來做的,就是挑一張圖片並取得 Uri。4.4 以上拿到的形如:

content://com.android.providers.media.documents/document/image%3A69983

舊版本則可能長這樣:

content://media/external/images/media/image%3A69983

如果業務上非得拿到檔案的絕對路徑(例如要交給某些只吃路徑的第三方 SDK),可依 Uri 的 authority 分頭處理:

public static String getPath(final Context context, final Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
            // TODO 非主分割區另行處理
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{ split[1] };
            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore 及其他一般 content Uri
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

/**
 * 取得該 Uri 的 _data 欄位值,適用於 MediaStore 與其他以檔案為基礎的 Provider
 */
public static String getDataColumn(Context context, Uri uri,
        String selection, String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = { column };
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

需要注意的是,上述「靠 _data 欄位反推路徑」的做法在新版 Android 上已逐漸失效,特別是 Google Drive 等雲端來源根本沒有對應的本機檔案。因此更推薦的思維是:把 Uri 當成一個可長期持有的資源憑證,直接用 ContentResolver 開啟流或檔案描述符來讀取,而不是執著於取得路徑字串。

SAF 這一部分就先談到這裡。真正要用到時再回頭細看實作細節即可,但有一點值得記住:4.4 之後取得檔案內容的方式,確實比過去簡單直觀許多。

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