首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android APK 安裝時自動導入資產檔案:assets 目錄 + 首次啟動解壓

     編輯:程式設計綜合問答

APK 安裝無法直接帶入外部檔案到裝置目錄,標準做法是將檔案打包進 assets,首次啟動時複製到內部/外部儲存空間。

實作步驟

  1. 將需導入的檔案(或壓縮包 zip)放入 src/main/assets/ 目錄。
  2. 啟動頁(Splash/Launcher Activity)檢查目標檔案是否存在,不存在則解壓:
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 解壓範例

注意事項

  • assets 檔案總大小建議 < 50MB,超過需考慮分包下載(OBB/動態分發)。
  • 若需對外部 App 可見,複製到 getExternalFilesDir(null) 並用 FileProvider 分享。
  • 首次啟動解壓會增加冷啟動時間,建議顯示進度條或放背景執行緒。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved