編輯:關於 Android 程式設計
做數獨遊戲時要加一個截圖功能,把當前遊戲畫面存成圖片。功能很簡單,程式碼也不長,結果卻卡了我好一陣子。
try {
Bitmap map = Bitmap.createBitmap(puzzleView.getDrawingCache());
saveBitmap(map);
Toast.makeText(this, R.string.screenshot_success, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, R.string.screenshot_fail, Toast.LENGTH_SHORT).show();
}
public void saveBitmap(Bitmap bitmap) throws Exception {
String dirPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator
+ "MySudoku" + File.separator
+ getString(R.string.diff_1 + diff);
File file = new File(dirPath);
if (!file.exists()) file.mkdirs();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
String date = sDateFormat.format(new java.util.Date());
String path = dirPath + File.separator + date + ".png";
manageFiles(file, ".png");
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
} catch (Exception e) {
out.close();
}
}
// 超過 3 張就刪掉多餘的
public void manageFiles(File dir, String extension) {
File[] files = dir.listFiles(getFilter(dir, extension));
if (files.length >= 3) {
for (int i = 2; i < files.length; i++) {
files[i].delete();
}
}
}
運行時不管怎麼試,總是在 new FileOutputStream(path) 這一行丟出異常。我把該檢查的都檢查了一遍:SD 卡權限有申請、目錄用 mkdirs() 建好了、Environment.getExternalStorageDirectory() 回傳的值也正常、除錯過程一路順利沒有其他錯誤訊息。就是找不到原因。
後來靈機一動,回頭盯著日期格式字串看:
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
我在電腦桌面上試著建立一個名稱裡帶冒號的文字檔,作業系統直接跳出錯誤——冒號是檔名保留字元,不能用來命名檔案。

對,BUG 就是這個。Android 底層是 Linux 檔案系統,技術上允許冒號出現在檔名中,但上層的 File 與各項系統服務在處理時並不保證一致,於是就在 FileOutputStream 這一步炸了。
把格式字串中的冒號換掉即可,最直白的做法是用時分秒之間不加分隔或改用其他合法字元:
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
這樣產生的檔名像 20260826225316.png,排序時也剛好符合時間先後,比原本的 yyyy-MM-dd-hh:mm:ss 更好用。
第一,檔名別用使用者可見的格式直接命名。除了冒號,Windows 相容性上還有 < > : " / \ | ? * 這一組保留字元;Android 上則要特別避開 / because 它會被當成路徑分隔符。若要保留可讀時間,用 yyyyMMdd_HHmmss 這種底線分隔最安全。
第二,那個 catch 區塊本身也有問題。
} catch (Exception e) {
out.close(); // 若 new FileOutputStream 就失敗,out 仍是 null
}
如果異常發生在 FileOutputStream 建立階段,out 會是 null,此行會再拋一次 NullPointerException,把原本真正的錯誤訊息掩蓋掉。這也是我當初查了那麼久的原因之一——日誌裡根本看不到關鍵資訊。正確做法是在 catch 中 e.printStackTrace(),並把 close 放到 finally 中加 null 判斷。
結論很樸素:檔名只用英數、底線與連字號,是最省事的自我保護。
淺談 EventBus:Android 發布訂閱事件總線
EventBus 是一款針對 Android 優化的發布/訂閱事件總線,主要用來替代 Intent、Handler、Broadcast 等元件,在 Activity、Fr
Android 日誌管理框架 NativeLogger 介紹
日誌是任何專案開發中的必備組件,它能記錄系統行為,幫助開發者排錯、優化效能、調整系統行為。既然日誌能做這麼多分析,開發者自然有各種定製需求,例如在不同環境過濾不同等級的
Android 讀取根目錄檔案與資料夾的實作方式
需求背景在某些 Android 應用中,開發者可能需要列出裝置根目錄下的檔案或資料夾,例如進行簡單的檔案瀏覽、除錯檢查或備份工具。這類功能的核心是使用 File 類別取得
Android 圖像繪製(二)畫布上放大縮小的位置問題
在 Android 中將圖像在畫布上放大縮小時,圖像的邊框大小並不會跟著改變! 原圖如下: 放大後:原圖的邊框沒有改變,位置依舊! 所以若要正確擺放圖片的位置,