如果您正在通过您的应用程序安装其他一些 APK 下载,并且在成功安装后想要删除,请关注我:-)
第 1 步:
在 AndroidManifest.xml 中声明以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_ADDED" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_CHANGED" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_INSTALL" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_REPLACED" />
第 2 步:
注册接收方
<receiver
android:name="com.az.appstore.InstallReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_CHANGED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<action android:name="android.intent.action.PACKAGE_INSTALL" />
<data android:scheme="package" />
</intent-filter>
</receiver>
第 4 步:
在您的安装程序活动中创建一个像这样的哈希映射,我在ApplicationMain 创建,它会根据实现而有所不同。
public static final ConcurrentHashMap<String, File> INSTALL_APK_INFO = new ConcurrentHashMap<String, File>();
并填写包名称和文件,其中放置了apk。您可以使用此方法从任何 apk 中获取 Pacakage 名称
public static String getPackageNameForAPK(final String archiveFilePath, Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageArchiveInfo(archiveFilePath, PackageManager.GET_META_DATA);
return info.packageName;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
第 5 步:
现在在您的安装接收器上执行此操作
if (action.equals(Intent.ACTION_PACKAGE_ADDED) || action.equals(Intent.ACTION_PACKAGE_CHANGED) || action.equals(Intent.ACTION_PACKAGE_INSTALL) || action.equals(Intent.ACTION_PACKAGE_REPLACED)) {
ApplicationInfo info = null;
try {
info = context.getPackageManager().getApplicationInfo(intent.getDataString().split(":")[1], PackageManager.GET_META_DATA);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (info != null) {
File file = ApplicationMain.INSTALL_APK_INFO.get(info.packageName);
if (file != null) {
file.delete();
ApplicationMain.INSTALL_APK_INFO.remove(info.packageName);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
总结
1) 创建一个 hashmap 并使用 APK 包名称和文件填充它。文件正是您的 APK 所在的位置。
请求安装 APK
public static void installUpdateAPK(Context context, String pathToAPK) {
pathToAPK = pathToAPK.replace("file:///", "");
final Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File(pathToAPK);
intent.setDataAndType(Uri.fromFile(file), APK_MIME_TYPE);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
String name = getPackageNameForAPK(pathToAPK, context);
if (name != null) {
ApplicationMain.INSTALL_APK_INFO.put(name, file);
}
}
2) 注册包添加、更改、安装意图
3) 在您的接收器上获取从Intent 安装的包名称
4) 从哈希图中获取文件对象,然后调用 delete()