Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 安裝與解除安裝程式的實作方式

編輯:進階開發

對開發者而言,Android 是相當實用的平台,可以自行開發各種應用程式滿足需求。其中「安裝與解除安裝」是最基礎卻常被忽略的能力,本文說明如何透過 Intent 呼叫系統的安裝器。

先看系統是怎麼做的

從 Android 安裝/解除安裝程式的原始碼可以看到,系統用兩個 Activity 分別處理這兩件事:

<activity android:name=".PackageInstallerActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="content" />
        <data android:scheme="file" />
        <data android:mimeType="application/vnd.android.package-archive" />
    </intent-filter>
</activity>

<activity android:name=".UninstallerActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <action android:name="android.intent.action.DELETE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="package" />
    </intent-filter>
</activity>

重點在 MIME type 與 scheme:安裝用 file / content scheme 搭配 application/vnd.android.package-archive;解除安裝則用 package scheme。理解這個對應關係,我們就能在自己的程式中觸發同樣的流程。

從 SD 卡安裝程式

String fileName = Environment.getExternalStorageDirectory() + "/myApp.apk";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)),
        "application/vnd.android.package-archive");
startActivity(intent);

這段程式碼會叫出系統安裝介面,由使用者確認後完成安裝。

解除安裝程式

Uri packageURI = Uri.parse("package:com.android.myapp");
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);

把套件名稱組進 package: URI,交給 ACTION_DELETE 即可。

處理「未知來源」的限制

Android 預設不允許安裝非官方市集取得的程式,因此安裝前最好先檢查這項設定:

int result = Settings.Secure.getInt(getContentResolver(),
        Settings.Secure.INSTALL_NON_MARKET_APPS, 0);
if (result == 0) {
    // 這裡可以顯示提示對話框說明情況
    // 並視需要直接開啟應用程式設定頁讓使用者自行開啟
    Intent intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_SETTINGS);
    startActivity(intent);
}

幾個實務注意事項

第一,從 Android 7.0 起,Uri.fromFile() 這類直接暴露 file:// URI 的寫法會引發 FileUriExposedException,必須改用 FileProvider 產生 content:// URI,並在 AndroidManifest 中設定對應的 <provider> 與 grantUriPermissions。

第二,静默安裝(不經使用者確認)需要系統簽章層級的權限,一般應用程式無法取得,因此上述做法都是「叫出安裝介面」而非真正靜默安裝。

第三,若要判斷某程式是否已安裝,可用 PackageManager.getPackageInfo() 並捕捉 NameNotFoundException,比直接嘗試安裝再處理錯誤更乾淨。

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