編輯:關於 Android 程式設計
需求很單純:已知 SD 卡上一張圖片的完整路徑,把它讀出來顯示在 ImageView 上。核心只有兩個 API——File.exists() 做前置檢查、BitmapFactory.decodeFile() 解碼。
package com.guo;
import java.io.File;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class MainAct extends Activity {
private ImageView img;
// SD 卡上的圖片路徑
private String filepath = "/sdcard/hot.png";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView) findViewById(R.id.img);
File file = new File(filepath);
if (file.exists()) {
Bitmap bm = BitmapFactory.decodeFile(filepath);
// 將圖片顯示到 ImageView
img.setImageBitmap(bm);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/img"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
讀取外部儲存空間必須在 AndroidManifest.xml 中聲明權限,否則 file.exists() 會回傳 false,而且不會給你任何錯誤提示——這是最容易誤判的地方。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Android 4.4(API 19)之前只需要 WRITE_EXTERNAL_STORAGE 就能讀寫;4.4 之後讀取要明確宣告 READ_EXTERNAL_STORAGE。到了 Android 6.0(API 23)以上,這還會變成執行期動態權限,必須主動向使用者請求。
程式碼很短,但直接搬到正式專案會遇到幾個問題:
/sdcard/hot.png 這種寫法在早期機型可行,但從 Android 4.4 開始,/sdcard 只是個指向實際掛載點的軟連結,多使用者環境下更是每個使用者一個獨立目錄。正確做法是用系統 API 取得:
// 取得外部儲存空間的根目錄 File dir = Environment.getExternalStorageDirectory(); // 更好的做法:取得 App 專屬的外部目錄,不需要任何權限 File appDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
getExternalFilesDir() 回傳的目錄在 App 解除安裝時會自動清除,而且不需要宣告任何儲存空間權限,是放置 App 自己產生的檔案的首選。若要讀取使用者的相簿,則應走 MediaStore。
BitmapFactory.decodeFile() 是同步的 I/O 加解碼操作。一張 1200 萬畫素的照片解成 ARGB_8888 的 Bitmap 需要約 48MB 記憶體,在主 thread 執行幾乎必定觸發 ANR 或 OutOfMemoryError。
實務上必須做兩件事:放到背景 thread,並在解碼前先取樣縮小。
decodeFile() 失敗時回傳 null 而不拋例外,接著 setImageBitmap(null) 不會報錯但畫面空白,很難查。應該判空並提供替代圖。
public class ImageLoaderTask extends AsyncTask<String, Void, Bitmap> {
private final ImageView target;
private final int reqWidth;
private final int reqHeight;
public ImageLoaderTask(ImageView view, int width, int height) {
this.target = view;
this.reqWidth = width;
this.reqHeight = height;
}
@Override
protected Bitmap doInBackground(String... paths) {
try {
// 第一趟:只讀取尺寸,不真正解碼
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(paths[0], opts);
// 依目標尺寸計算取樣率
opts.inSampleSize = calculateInSampleSize(opts, reqWidth, reqHeight);
opts.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(paths[0], opts);
} catch (OutOfMemoryError e) {
return null;
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
target.setImageBitmap(bitmap);
} else {
target.setImageResource(R.drawable.default_placeholder);
}
}
/**
* 計算合適的取樣率。inSampleSize 只能是整數,
* 取 2 的次方對多數解碼器來說效能最佳。
*/
private static int calculateInSampleSize(BitmapFactory.Options opts,
int reqWidth, int reqHeight) {
final int height = opts.outHeight;
final int width = opts.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
// 使用方式
ImageView img = findViewById(R.id.img);
int size = getResources().getDimensionPixelSize(R.dimen.thumb_size);
new ImageLoaderTask(img, size, size).execute("/sdcard/hot.png");
這個版本解決了原範例的三個問題:inJustDecodeBounds = true 讓第一趟只讀取檔案頭取得尺寸而不配置像素記憶體,據此算出取樣率後第二趟才真正解碼;解碼在背景 thread 進行;並對 null 與 OutOfMemoryError 都做了處理。
最後補充一點:如果你只是想顯示 SD 卡上的圖片,而它其實是由相機或相簿產生的,那更合適的做法是查詢 MediaStore.Images.Media,用 ContentResolver 拿到 URI,再搭配 Glide 或 Coil 這類成熟的圖片載入庫。它們已經把快取、取樣、生命週期綁定、請求取消都處理好了,除非有特殊需求,否則沒必要自己實作。
Android 開發性能優化總結(二):UI 渲染與記憶體管理
接續上一篇《Android 開發性能優化總結(一)》。 一、UI 性能檢測與優化 UI 是應用與用戶接觸最直接的一層。流不流暢,用戶是能感覺出來的——輕則影響心情,重則
動手打造Android 3D翻頁動畫:自定義Rotate3D完整實作
想讓App的頁面切換更有質感嗎?本文帶你動手實作一款帶有立體感的3D滑動翻頁動畫,透過自定義Animation類別,讓畫面像書頁一樣沿著Y軸翻轉,兼顧視覺效果與程式碼的靈
純手寫一個 Android 朋友圈:列表、多圖選擇與視頻拍攝全流程
朋友圈這種「頭像 + 文字 + 九宮格圖片/視頻」的形態,是社交類應用的標配。前幾天動手寫了一個小 demo,把整個鏈路走了一遍:動態列表渲染、多圖選擇與數量限制、視頻錄
微信發不出語音怎麼辦?從網路到快取資料的排查順序
微信最常用的功能就是語音,一旦發不出去,整個溝通就卡住。這個問題看起來嚴重,但多數情況可以用幾個步驟自己解決。先排除最常見的原因語音傳送失敗,多半來自網路問題:訊號不穩、