編輯:關於 Android 程式設計
讀完上一篇,你應該已經能熟練使用系統提供的 ContentProvider,也能自己動手寫一個。但官方文件裡其實還藏著幾個現成的 Provider,值得認識一下:
在 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 帶來幾個實用特性:使用者可以瀏覽所有 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 開啟 → 使用者挑選 → 取得檔案相關資訊。
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 之後,就可以透過 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 為單位的大小。
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;
}
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);
如果你希望自家 App 的資料也能在 DocumentsUI 中被瀏覽,就得自己寫一個 provider。註冊步驟如下:
<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;
}
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 之後取得檔案內容的方式,確實比過去簡單直觀許多。
DrySister 圖片應用實作:加入 SQLite 離線快取
為什麼需要資料快取 在 DrySister 的第一版中,我們已經加入非同步圖片載入與記憶體、磁碟快取。不過,若只在有網路時取得圖片資訊,一旦離線後重新進入 App,雖然圖
深入排查:Android 应用被强杀或回收引发空指针崩溃的根治方案
一、问题是如何发生的,又会在什么情况下发生? 当使用者动用手机清理助手,或后台回收机制将我们的应用进程杀死时,就有可能冒出这类空指针问题。下面不妨借一个例子,一同看看这种
用 RecyclerView 實現橫向分頁 GridView 效果
昨天收到設計師的設計稿,需求是做出「橫向分頁」的效果,而且第二頁要預設露出來一小部分,用來提示用戶「這裡可以左右滑動」。先上效果圖: 看到這種橫向滑動分頁,第一直覺就是
Android 官方 MVP 架構解析:從 todo-mvp 看職責分離
MVP 是 Android 開發中常見的架構模式之一,全名為 Model View Presenter。它從 MVC 演進而來,主要目的在於降低 View 與業務邏輯之間