基本思路:用www下载服务器上的apk储存于persistentPath,然后调用android方法安装apk完成更新。
1.下载apk
IEnumerator InstallApk()
{
WWW www = new WWW(url);
//下载需要更新的apk
while (true)
{
Debug.Log(www.progress / 1f * 100);
if (www.isDone)
{
break;
}
yield return null;
}
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log("error:" + www.error);
yield return 0 ;
}
try
{
//将apk写入沙盒目录
string path = Application.persistentDataPath + "/test.apk";
File.WriteAllBytes(path, www.bytes);
using(AndroidJavaClass cl = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
using(AndroidJavaObject ob = cl.GetStatic<AndroidJavaObject>("currentActivity"))
{
//然后调用android来安装apk
ob.Call("InstallApk", path);
}
}
}
catch (System.Exception e)
{
Debug.Log(e);
}
}
2.安装apk (java代码)
public void InstallApk(String path)
{
Log.d("----------", path);
url = path;
Log.d("url:", url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
startActivity(intent);
}
3.打开apk
public void openApk(Context context) {
Log.d("OpenApkUrl:" ,url);
PackageManager manager = context.getPackageManager();
// 这里的是你下载好的文件路径
PackageInfo info = manager.getPackageArchiveInfo(url, PackageManager.GET_ACTIVITIES);
if (info != null) {
Intent intent = manager.getLaunchIntentForPackage(info.applicationInfo.packageName);
startActivity(intent);
}
}
这段代码有点异议,原思路是监听apk安装完毕后调用该方法,但android似乎不支持自监听,就是说广播接收者(监听用)所在的apk被销毁后无法监听到自己被销毁。