以编程方式安装/卸载APK(PackageManager vs意图)

以编程方式安装/卸载APK(PackageManager vs意图)

我的应用程序安装了其他应用程序,它需要跟踪它安装了哪些应用程序。当然,这可以通过简单地保存已安装应用程序的列表来实现。但这不应该是必要的!PackageManager应该负责维护installedBy(a,b)关系。实际上,根据API,它是:

公共抽象字符串getInstallerPackageName(StringPackageName)-检索安装包的应用程序的包名。这将识别该软件包来自哪个市场。

现行方法

使用意向安装APK

Intent intent = new Intent(Intent.ACTION_VIEW);intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
startActivity(intent);

使用意图卸载APK:

Intent intent = new Intent(Intent.ACTION_DELETE, Uri.fromParts("package",getPackageManager().getPackageArchiveInfo(apkUri.getPath(), 0).
packageName,null));startActivity(intent);

这显然不是Android Market安装/卸载软件包的方式。他们使用更丰富版本的PackageManager。这可以通过从AndroidGit存储库下载Android源代码来看到。下面是两个与意图方法相对应的隐藏方法。不幸的是,外部开发人员无法使用它们。但也许他们会在未来?

更好的方法

使用PackageManager安装APK

/**
 * @hide
 * 
 * Install a package. Since this may take a little while, the result will
 * be posted back to the given observer.  An installation will fail if the calling context
 * lacks the {@link android.Manifest.permission#INSTALL_PACKAGES} permission, if the
 * package named in the package file's manifest is already installed, or if there's no space
 * available on the device.
 *
 * @param packageURI The location of the package file to install.  This can be a 'file:' or a
 * 'content:' URI.
 * @param observer An observer callback to get notified when the package installation is
 * complete. {@link IPackageInstallObserver#packageInstalled(String, int)} will be
 * called when that happens.  observer may be null to indicate that no callback is desired.
 * @param flags - possible values: {@link #INSTALL_FORWARD_LOCK},
 * {@link #INSTALL_REPLACE_EXISTING}, {@link #INSTALL_ALLOW_TEST}.
 * @param installerPackageName Optional package name of the application that is performing the

差异

  • 当使用意图时,本地包管理器不知道安装来自哪个应用程序。具体来说,getInstallerPackageName(.)返回NULL。

  • 隐藏方法安装包(.)将安装程序包名称作为参数,并且最有可能设置此值。

问题

是否可以使用intents指定包安装程序名称? (也许可以在安装意图之外添加安装程序包的名称?)

提示:如果您想下载Android源代码,可以按照这里描述的步骤:下载源代码树。要提取*.java文件并根据包层次结构将它们放在文件夹中,您可以查看这个整洁的脚本:查看Eclipse中的Android源代码.


犯罪嫌疑人X
浏览 1220回答 3
3回答

德玛西亚99

Android P+在AndroidManifest.xml中需要此权限。<uses-permission&nbsp;android:name="android.permission.REQUEST_DELETE_PACKAGES"&nbsp;/>然后:Intent&nbsp;intent&nbsp;=&nbsp;new&nbsp;Intent(Intent.ACTION_DELETE);intent.setData(Uri.parse("package:com.example.mypackage"));startActivity(intent);卸载。似乎更容易.。
打开App,查看更多内容
随时随地看视频慕课网APP