編輯:關於 Android 程式設計
做問題反饋頁面時,需要讓用戶上傳截圖。最初的念頭是把設備裡所有圖片都掃描出來自己列清單,寫到一半才反應過來——系統相冊本來就有現成的 API 可以調起,何必自己造輪子。
效果如下:

用 ACTION_PICK 搭配 MediaStore 的圖片 URI,系統就會打開相冊供用戶挑選:
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
用 startActivityForResult 而非 startActivity,是因為我們需要拿回用戶的選擇結果。請求碼 1 會在回呼中與其他請求區分開來。
回調裡要做的事有四步:從 data 取出 URI → 由 URI 反查真實檔案路徑 → 讀取原圖尺寸 → 按比例縮放後解碼。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// 由 ContentResolver 反查本機路徑
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// 第一輪:只讀邊界,不載入像素,避免大圖 OOM
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, opts);
// 計算成 160*160 左右的大小
opts.inSampleSize = computeSampleSize(opts, -1, 160 * 160);
// 用完務必改回 false,否則只會拿到一個空寬高的 Bitmap
opts.inJustDecodeBounds = false;
try {
Bitmap bmp = BitmapFactory.decodeFile(picturePath, opts);
if (mPosition != 0) {
// 替換既有項
fba.getmImgs().set(mPosition, bmp);
fba.getmImgPaths().set(mPosition, picturePath);
} else {
// 新增一項
fba.getmImgs().add(bmp);
fba.getmImgPaths().add(picturePath);
}
} catch (OutOfMemoryError err) {
err.printStackTrace();
}
fba.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
這段代碼裡最容易翻車的一行是 opts.inJustDecodeBounds = false。用了同一個 Options 物件兩次,若忘了把它改回來,第二次 decodeFile 依然只讀邊界,拿到的就是一個寬高為 -1 的空殼。
Android 要求 inSampleSize 為整數,解碼時寬高會各除以這個值。下面這組方法是經典的兩段式計算:先算出理論上的初始值,再對齊到合適的整數(8 以內取 2 的冪次,超過 8 則對齊到 8 的倍數,兼顧效能與記憶體對齊)。
public int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
// 依「最大像素數」推算的下限
int lowerBound = (maxNumOfPixels == -1) ? 1
: (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
// 依「最短邊」推算的上限
int upperBound = (minSideLength == -1) ? 128
: (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
URI 未必能換成檔案路徑。MediaStore.Images.Media.DATA 這條路在 Android 4.4 之後逐步失效,到了 Android 10(API 29)分區儲存正式上線,getExternalStorage 的絕對路徑基本取不到了,查詢結果可能為 null。較新的做法有兩種:一是用 ContentResolver.openInputStream(uri) 直接讀串流,配合 BitmapFactory.decodeStream;二是用 requestLegacyExternalStorage 暫時兼容,但這只是過渡方案,不建議新專案採用。
Cursor 記得關。示例有 cursor.close(),但更穩妥的是用 try-with-resources 或 useCursor 之類的機制,避免路徑中途出錯導致洩漏。
只 catch OutOfMemoryError 並不夠。它被吞掉之後 mImgs 裡可能多出一個 null 元素,後續渲染才炸。合理的做法是在解碼失敗時給使用者明確提示,或預先檢查檔案大小並直接拒絕過大圖片。
別忘了 registerForActivityResult。onActivityResult 在元件化、AndroidX 導向的今天已屬舊寫法,改用 ActivityResultContracts.PickVisualMedia(Android 13+ 甚至有專用的相冊挑選器,無需任何儲存權限)能省下大量相容性判斷,也更符合現在的分區儲存模型。
總結起來,圖片選取的難點從來不在「調起相冊」那一行 Intent,而在拿到 URI 之後如何可靠地讀出位圖——路徑解析、尺寸取捨、記憶體控制,這三件事才是真正需要小心的地方。
Android 支付接入實戰:Google In-app Billing V3
因為公司需要接入 Google 的應用內支付(即 Google In-app Billing V3),接入過程中查閱了大量文章,也遇到不少問題,因此想和大家分享交流一下心
Android 如何判斷 App 的前後台狀態?一篇講透常見方案
在專案開發中,我們常常需要在 App 從後台切回前台的那一刻執行某些操作,比如檢查版本更新、刷新資料。自己動手實作之後,我發現對背後的機制其實一知半解,於是查了些資料,把
Android 程式碼混淆設定:ProGuard 兩種配置方式說明
Android 本身就整合了程式碼混淆能力,相關工具位於 Android SDK 的 tools/proguard 目錄下。我們只需在專案中做簡單設定即可啟用。 初始的設
Android 學習教程:周視圖日曆庫 WeekView 使用詳解(第十五篇)
本篇筆記聚焦於一個靈活的周視圖日曆庫 WeekView,帶大家實現以「天/周」為單位的日程展示。示例包含本地假數據填充與異步網絡加載兩種模式,並支持日、三日、周多種視圖切