问题描述
我有一个来自 this
的代码,可以统一安装apk,但在Android中不起作用7.0,因为不再支持Uri.fromfile
,现在应该使用FileProvider.getUriForFile
.
I have a code from this
answer code in unity to install an apk but it does not work in Android 7.0 because Uri.fromfile
is no longer supported and FileProvider.getUriForFile
should now be used.
我尝试在android studio中打开项目,并按照本教程操作清单文件- https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/zh-CN
I tried opening the project in android studio and followed this tutorial to manipulate the manifest file - https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en
AndroidJavaClass intentObj = new
AndroidJavaClass("android.content.Intent");
string ACTION_VIEW = intentObj.GetStatic<string>("ACTION_VIEW");
int FLAG_ACTIVITY_NEW_TASK = intentObj.GetStatic<int>
("FLAG_ACTIVITY_NEW_TASK");
AndroidJavaObject intent = new
AndroidJavaObject("android.content.Intent", ACTION_VIEW);
AndroidJavaObject fileObj = new AndroidJavaObject("java.io.File",
apkPath);
AndroidJavaClass uriObj = new AndroidJavaClass("android.net.Uri");
AndroidJavaObject uri = uriObj.CallStatic<AndroidJavaObject>
("fromFile", fileObj);
intent.Call<AndroidJavaObject>("setDataAndType", uri,
"application/vnd.android.package-archive");
intent.Call<AndroidJavaObject>("addFlags", FLAG_ACTIVITY_NEW_TASK);
intent.Call<AndroidJavaObject>("setClassName",
"com.android.packageinstaller",
"com.android.packageinstaller.PackageInstallerActivity");
AndroidJavaClass unityPlayer = new
AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity =
unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
currentActivity.Call("startActivity", intent);
推荐答案
只需替换
AndroidJavaObject fileObj = new AndroidJavaObject("java.io.File", apkPath);
AndroidJavaClass uriObj = new AndroidJavaClass("android.net.Uri");
AndroidJavaObject uri = uriObj.CallStatic<AndroidJavaObject>("fromFile", fileObj);
使用
AndroidJavaObject fileObj = new AndroidJavaObject("java.io.File", apkPath);
AndroidJavaClass fileProvider = new AndroidJavaClass("android.support.v4.content.FileProvider");
AndroidJavaObject uri = fileProvider.CallStatic<AndroidJavaObject>("getUriForFile", unityContext, authority, fileObj);
authority
参数的构造方式为:
string packageName = unityContext.Call<string>("getPackageName");
string authority = packageName + ".fileprovider";
然后在调用currentActivity.Call
函数之前向意图添加FLAG_GRANT_READ_URI_PERMISSION
权限.
Then add FLAG_GRANT_READ_URI_PERMISSION
permission to the intent before calling currentActivity.Call
function.
intent.Call<AndroidJavaObject>("addFlags", FLAG_GRANT_READ_URI_PERMISSION);
有关完整脚本,请参见现在编辑的 如何从统一应用程序安装Android APK 问题.
For the complete script see the now edited How to install Android apk from unity application question.
这篇关于如何在Unity中将Uri.fromfile转换为FileProvider.getUriForFile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!