unity下载安装包并且安装的过程

本方法可以通过没有热更新,下载需要升级的版本,并且安装。不过安装包不要太大,通过unity中www的方法下载。调用安卓自身的安卓方法,具体代码如下:

 IEnumerator DownFile(string url)
    {
        Debug.Log("开始下载");
        WWW www = new WWW(url);
        while (!www.isDone)
        {
            string LoadPro = (((int)(www.progress * 100)) % 100) + "%";
            Debug.Log("进度:" + LoadPro);
            yield return 1;
        }
        yield return www;
        if (www.isDone)
        {
            Debug.Log("下载完成");
            byte[] bytes = www.bytes;
            CreatFile(bytes);
            this.InstallAPK(holdPath, true);
            //yield return 1;
        }
    }
    void CreatFile(byte[] bytes)
    {
        Stream stream;
        //text_test.GetComponent<Text>().text = holdPath;
        Debug.Log("下载地址" + holdPath);
        FileInfo file1 = new FileInfo(holdPath);
        stream = file1.Create();
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
        stream.Dispose();
    }
    /// <summary>
    /// 安装apk包
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="bReTry"></param>
    /// <returns></returns>
    public bool InstallAPK(string path, bool bReTry)
    {
        try
        {
            var Intent = new AndroidJavaClass("android.content.Intent");
            var ACTION_VIEW = Intent.GetStatic<string>("ACTION_VIEW");
            var FLAG_ACTIVITY_NEW_TASK = Intent.GetStatic<int>("FLAG_ACTIVITY_NEW_TASK");
            var intent = new AndroidJavaObject("android.content.Intent", ACTION_VIEW);


            var file = new AndroidJavaObject("java.io.File", path);
            var Uri = new AndroidJavaClass("android.net.Uri");
            var uri = Uri.CallStatic<AndroidJavaObject>("fromFile", file);


            intent.Call<AndroidJavaObject>("setDataAndType", uri, "application/vnd.android.package-archive");


            if (!bReTry)
            {
                intent.Call<AndroidJavaObject>("addFlags", FLAG_ACTIVITY_NEW_TASK);
                intent.Call<AndroidJavaObject>("setClassName", "com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
            }


            var UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            var currentActivity = UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
            currentActivity.Call("startActivity", intent);


            Debug.Log("Install New Apk Ok");
            return true;
        }
        catch (System.Exception e)
        {
            Debug.LogError("Error Install APK:" + e.Message + " -- " + e.StackTrace + "  bRetry=" + bReTry);
            return false;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_33515628/article/details/79377815
今日推荐