核心代码
1,unity 端
public void InstallApk()
{
Debug.Log(Application.identifier);
AndroidJavaClass jcPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject joActivity = jcPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaClass install = new AndroidJavaClass("com.example.installapks.installApk");
//InstallApk
install.CallStatic("InstallApk", new object[] { Path.Combine(Application.persistentDataPath, "a.apk"), joActivity, Application.identifier });
}
2,android 端
/**
* 启动安装APK
*/
public static void InstallApk(String apkPath, Activity currentActivity,String packagename) {
System.out.println("Android下载地址:"+apkPath);
File file = new File(apkPath);
Intent intent = new Intent(Intent.ACTION_VIEW);
String str5 = Environment.getExternalStorageState(file);
if(Build.VERSION.SDK_INT>=24) { //Android 7.0及以上
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// 参数2 清单文件中provider节点里面的authorities ; 参数3 共享的文件,即apk包的file类
Uri apkUri = FileProvider.getUriForFile(currentActivity.getBaseContext(), packagename+".fileProvider", file);//记住修改包名
// 对目标应用临时授权该Uri所代表的文件
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
}else{
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
currentActivity.startActivity(intent);
}
Android 7.0之后需要 权限问题 AndroidManifest文件需要加
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
provider_paths文件
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="publicDir" path=""/>
</paths>
如有写的不明白的可以直接下载我的项目源码
附上项目下载地址 https://download.csdn.net/download/qq_39735878/13772619