问题
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.
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);
回答1:
Just replace
AndroidJavaObject fileObj = new AndroidJavaObject("java.io.File", apkPath);
AndroidJavaClass uriObj = new AndroidJavaClass("android.net.Uri");
AndroidJavaObject uri = uriObj.CallStatic<AndroidJavaObject>("fromFile", fileObj);
with
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);
The authority
parameter is constructed with:
string packageName = unityContext.Call<string>("getPackageName");
string authority = packageName + ".fileprovider";
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);
For the complete script see the now edited How to install Android apk from unity application question.
来源:https://stackoverflow.com/questions/45051350/how-to-convert-from-uri-fromfile-to-fileprovider-geturiforfile-in-unity