使用Intent安装apk的方法

来源:互联网 发布:围巾的各种围法 知乎 编辑:程序博客网 时间:2024/06/01 19:32

Install and Uninstall Android applications with Android PackageInstaller

 

This is actually very simple.

See PackageInstaller code here:http://android.git.kernel.org/?p=platform/packages/apps/PackageInstaller.git;a=tree;h=refs/heads/donut;hb=refs/heads/donut

Intent filters for such actions are:

<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

so if you want to install your .apk file from SD card – just write something like that:



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);

for uninstallation:


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


be aware that by default INSTALL_NON_MARKET_APPS option is disabled. You may want to check this option and show user friendly dialog before trying to install the app:



int result = Settings.Secure.getInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS, 0);
if (result == 0) {
    // show some dialog here
    // ...
    // and may be show application settings dialog manually
    Intent intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_SETTINGS);
    startActivity(intent);
}

if you want to uninstall your app by default from Pakage Manager then remove the category.DEFAULT line from uninstall app AndroidManifest.xml


 应用软件经常会因为功能的增加而升级,升级经常是在客户端给用户升级的提示,然后用户下载最新的apk程序包,软件升级过程大多数需要在线完成。 
 android 在线安装apk程序包,主要用到系统自带的apk安装器进行安装。用到系统自带的apk安装器安装apk包,首先需要在配置文件中加入权限声明

<uses-permission android:name="android.permission.INTERNET"></uses-permission>     <uses-permission android:name="android.permission.INSTALL_PACKAGES"></uses-permission>     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission