本文說明如何在 Android 手機或平板上抓取當前畫面,並把圖片存進 SD 卡的指定資料夾。核心概念只有三步:建立一塊與螢幕同尺寸的 Bitmap、從 DecorView 的繪製快取取得畫面、最後把 Bitmap 壓縮寫檔。
/**
* 獲取並保存當前螢幕截圖
*/
private void GetandSaveCurrentImage()
{
// 1. 建立 Bitmap
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
int w = display.getWidth();
int h = display.getHeight();
Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
// 2. 取得螢幕畫面
View decorview = this.getWindow().getDecorView();
decorview.setDrawingCacheEnabled(true);
Bmp = decorview.getDrawingCache();
String SavePath = getSDCardPath() + "/AndyDemo/ScreenImage";
// 3. 保存 Bitmap
try {
File path = new File(SavePath);
String filepath = SavePath + "/Screen_1.png";
File file = new File(filepath);
if (!path.exists()) {
path.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = null;
fos = new FileOutputStream(file);
if (null != fos) {
Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
Toast.makeText(mContext, "截圖已保存至 SDCard/AndyDemo/ScreenImage/ 下",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 取得 SD 卡根目錄路徑
*/
private String getSDCardPath(){
File sdcardDir = null;
// 判斷 SD 卡是否掛載
boolean sdcardExist = Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED);
if (sdcardExist) {
sdcardDir = Environment.getExternalStorageDirectory();
}
return sdcardDir.toString();
}
只要涉及外部儲存空間的讀寫,就必須在 AndroidManifest.xml 中宣告權限,否則寫檔會直接失敗:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
這種做法利用的是 View 的繪製快取,因此只能攔截「應用程式自己的視圖」,拿不到系統狀態列、通知欄或其他 App 的畫面。若要真正的全螢幕截圖,需要走系統級 API 或使用者授權的螢幕擷取服務。
另外,DrawingCache 使用完畢後記得呼叫 setDrawingCacheEnabled(false) 釋放記憶體;寫檔時把 flush() 與 close() 放在同一個流程裡,也要留意例外狀況下檔案可能只寫了一半。新版本的 Android 對外部儲存空間與執行期權限有更嚴格的限制,實作時記得先向使用者動態索取授權。