Unity Android 下載安裝開啟apk
阿新 • • 發佈:2018-11-22
基本思路:用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被銷燬後無法監聽到自己被銷燬。