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

用程式碼安裝與卸載 Android APK 的完整實作

編輯:關於 Android 程式設計

想在自己的 App 裡做「安裝」與「卸載」按鈕,靠的是 Intent 加上正確的 action 與 data。核心關鍵在這一行:

intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

第一個參數是要安裝的 apk 檔案路徑,第二個參數則是 apk 對應的 MIME 類型。這個類型字串可以在 Tomcat 安裝目錄下 conf 資料夾的 web.xml 中找到。

程式執行結果如下:

一、版面檔 main.xml

用 android:onClick 直接把按鈕綁到 Activity 的方法上,省去 findViewById 的麻煩:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="安裝"
        android:onClick="install"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="卸載"
        android:onClick="uninstall"
        />
</LinearLayout>

二、MainActivity

package com.njupt.install;

import java.io.File;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void install(View v) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        File file = new File(Environment.getExternalStorageDirectory(), "HtmlUI1.apk");
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    public void uninstall(View v) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:com.njupt.htmlui1"));
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

兩個 action 的差別

  • 安裝用 Intent.ACTION_VIEW,搭配 apk 檔案的 Uri 與 application/vnd.android.package-archive 類型,系統會跳出安裝確認畫面。
  • 卸載用 Intent.ACTION_DELETE,data 是 package: 開頭加上「套件名稱」的 Uri,注意這裡要填的是 package name,不是 apk 檔名。

實務提醒: apk 檔要放在應用程式可讀的位置(例如外部儲存空間),並在 AndroidManifest.xml 註冊 READ_EXTERNAL_STORAGE 權限;在 Android 7.0 以上,透過 Uri.fromFile() 會引發 FileUriExposedException,需改用 FileProvider 產生 content:// 類型的 Uri 才行。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved