APK 安裝無法直接帶入外部檔案到裝置目錄,標準做法是將檔案打包進 assets,首次啟動時複製到內部/外部儲存空間。
src/main/assets/ 目錄。private void copyAssetsIfNeeded() {
File targetDir = new File(getFilesDir(), "mydata"); // 內部儲存,免權限
File flag = new File(targetDir, ".extracted");
if (flag.exists()) return; // 已解壓
try {
// 解壓 zip 範例
InputStream is = getAssets().open("data.zip");
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
File outFile = new File(targetDir, entry.getName());
if (entry.isDirectory()) {
outFile.mkdirs();
} else {
outFile.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(outFile);
byte[] buffer = new byte[4096];
int len;
while ((len = zis.read(buffer)) > 0) fos.write(buffer, 0, len);
fos.close();
}
zis.closeEntry();
}
zis.close();
flag.createNewFile(); // 標記完成
} catch (IOException e) {
e.printStackTrace();
}
}
完整解壓工具類:Android Assets 解壓範例
getExternalFilesDir(null) 並用 FileProvider 分享。