Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

如何在 App 內安裝 assets 目錄下的 APK

編輯:關於 Android 程式設計

有些應用需要預先內嵌一個 APK 並在使用時安裝,例如插件化、離線升級包或內建工具模組。由於 assets 目錄是唯讀的,安裝前必須先把檔案複製到外部儲存空間,再發送安裝 Intent。

整個流程只有兩步:複製檔案、彈出確認框並啟動系統安裝器。

public class MainActivity extends Activity {
    Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;

        String targetPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.apk";

        if (copyApkFromAssets(this, "test.apk", targetPath)) {
            new AlertDialog.Builder(mContext)
                    .setIcon(R.drawable.ic_launcher)
                    .setTitle("安裝提示")
                    .setMessage("是否安裝?")
                    .setPositiveButton("yes", new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setDataAndType(
                                    Uri.parse("file://" + Environment
                                            .getExternalStorageDirectory().getAbsolutePath() + "/test.apk"),
                                    "application/vnd.android.package-archive");
                            mContext.startActivity(intent);
                        }
                    })
                    .show();
        }
    }

    /** 把 assets 中的檔案複製到指定路徑 */
    public boolean copyApkFromAssets(Context context, String fileName, String path) {
        boolean copyIsFinish = false;
        try {
            InputStream is = context.getAssets().open(fileName);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            copyIsFinish = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return copyIsFinish;
    }
}

幾個實務上會踩到的坑:

  • MIME 類型必須正確。dataAndType 的第二個參數要固定為 application/vnd.android.package-archive,寫錯系統就不會把它當成安裝檔處理。
  • Android 7.0 以上不建議用 file:// URI。此版本的 FileUriExposedException 會直接讓程式崩潰,正確做法是改用 FileProvider 產生 content:// URI,並在清單檔中宣告對應的 provider 與檔案路徑。
  • 記得申請儲存空間權限,否則寫檔會失敗;同時使用者需在系統設定中允許「安裝未知來源應用」。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved