
折腾了一天一夜未果。首先我要安装的 apk 的路径是下载到公共 Download 目录下的一个文件,所有文件的访问权限都允许了的,file:///storage/emulated/0/Download/timetr-38.apk 。然后通过 FileProvider.getUriForFile 得到 Uri 后发送隐式 Itent 去安装,三星手机安装提示“解析软件包出现问题。”,我的 Android 手机版本是 14 ,首先安装包肯定没有问题,我去文件管理手动安装尝试过,查看 AndroidStudio 控制台日志后发现的:
Cannot parse package content://com.xuebinduan.tomatotimetracker.fileprovider/root-path/file%3A/storage/emulated/0/Download/timetr-38.apk. Assuming defaults. stageApk: InstallData{ mApkInfo=ApkInfo{mUri=content://com.xuebinduan.tomatotimetracker.fileprovider/root-path/file%3A/storage/emulated/0/Download/timetr-36.apk, mSourceFilePath='/file:/storage/emulated/0/Download/timetr-36.apk', mStagedFile='null', mPackageInfo=null} , mOriginAppInfo=OriginAppInfo{uid=11153, packageName='com.xuebinduan.tomatotimetracker', AttributiOnTag='null', isGATest=false, originalUri=null, referrerUri=null, installerPackageName='null', isTrustedSource=false, returnResult=false} , mSessiOnId=-1 , mySessiOnId=-1 , mStagedSessiOnId=967735638 , mDeleteApkWhenFinished=true , action='android.intent.action.VIEW'} 我个人认为问题要么出在 FileProvider ,要么就是需要 DocumentFile ?但是 DocumentFile 也试过,可能是获取 DocumentFile 的方式不对,发现更有问题。但问题肯定出在 Uri 上。
我的代码如下:
AndroidManifest.xml
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> <provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissiOns="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider> file_paths
<external-path name="update_apk" path="Download/"/> <root-path name="root-path" path="." /> 安装 apk 的代码
private void installAPK(String apkFilePath) { if (!TextUtils.isEmpty(apkFilePath)) { Intent install = new Intent(Intent.ACTION_VIEW); install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); install.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true); //表明不是未知来源 File apkFile = new File(apkFilePath); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri cOntentUri= FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileprovider", apkFile); install.setDataAndType(contentUri, "application/vnd.android.package-archive"); } else { install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); } activity.startActivity(install); } } build.gradle
compileSdk 33 targetSdkVersion 30 1 murmur 2024-02-07 17:05:34 +08:00 new Intent(Intent.ACTION_INSTALL_PACKAGE) 难道不是要用这个 intent 么 |