天天看點

Unity3d+虛拟城市:更新,登入流程:APK更新,資源更新,注冊登入

程式入口

VirtualCityMgr

做了幾件事

  1. 設定分辨率
  2. 設定幀率
  3. 移動端啟動log記錄
  4. 啟動緩沖池
  5. 啟動TimeManager
  6. 啟動版本更新,資源更新,AssetMgr
  7. 啟動讀配置表
  8. 啟動sdk相關(wxpay,alipay)
void Start()
   {
       m_instance = this;

       if (Application.isMobilePlatform == false)
       {
           DataMgr.m_resolution = 1.0f;
       }
       int width = (int)(Screen.currentResolution.width * DataMgr.m_resolution);
       int height = (int)(Screen.currentResolution.height * DataMgr.m_resolution);
       Screen.SetResolution(width, height, true);

       Debug.Log("螢幕分辨率:" + Screen.width + "," + Screen.height);
       Screen.sleepTimeout = SleepTimeout.NeverSleep;
       Application.targetFrameRate = 30;

       m_tarns = this.transform;
       if (Application.isMobilePlatform == true)
       {
           MyLogCallback.Instance.Startup();
       }

       //if (PublicFunc.IsExistFile("NewGuide.txt") == false)
       //{
       //    DataMgr.m_isNewGuide = true;
       //}
       //啟動全局緩沖池
       PoolMgr.Instance.StartUp();

       //啟動消息中心
       MessageCenter.Instance.StartUp();
       Framework.Tools.TimeManager.Instance.StartUp();
       SmssMgr.Instance.StartUp();
       Loom.Current.StartUp();
       HttpMgr.Instance.Startup();
       SpProto.StartUp();
#if UNITY_EDITOR && EditorLoadAb

       VcData.Instance.LoadData(Init);
#else
       AssetMgr.Instance.Init(Init);
#endif 

       if (Application.platform == RuntimePlatform.IPhonePlayer)
       {
           AliComponent.Instance.Startup();
           WeChatComponent.Instance.Startup();
       }      

APK更新

  1. 本地大版本号比對伺服器cdn下BigVersion.txt,裡面包含大版本号和apk包大小資訊
  2. 不一緻啟動下載下傳apk,下載下傳完後啟動安裝apk。
  3. 大版本更新安裝下好的apk,相容任意安卓5.0,7.0,8.0版本
IEnumerator doBigVersionUpdate()
    {
        
        string dataPath = AppConst.BigVerionSavePath + "/"; //資料目錄
        string url = AppConst.BigVersionDownUrl + "/";
        string apkName = "vc.apk";
        if (Directory.Exists(AppConst.BigVerionSavePath) == false)
        {
            Directory.CreateDirectory(AppConst.BigVerionSavePath);
        }
        WWW www = new WWW(url + "BigVersion.txt");
        yield return www;
        if (www.error != null)
        {
            Debug.LogError("大版本檢測失敗:" + www.error.ToString());
            //StartGameManager();
            Debug.Log("不能更新,開始遊戲");
            
            yield break;
        }

        string[] remoteVersion = www.text.Split('|');
        if (remoteVersion[0] == VirtualCityMgr.m_instance.m_bigVersion)
        {
            Debug.Log("大版本一緻");
        }
        else
        {
            m_isBigVersionUpdate = true;
            DataMgr.m_downTotal = long.Parse(remoteVersion[1]) * 1024 * 1024;
            List<string> updateUrls = new List<string>();
            List<string> updateFiles = new List<string>();
            updateUrls.Add(url + apkName);
            updateFiles.Add(dataPath + apkName);
            UIManager.Instance.PushPanelFromRes(UIPanelName.firstpanel, UIManager.CanvasType.Screen);
            if (DataMgr.m_downTotal > 0)
            {
                ispanel ispanel = (ispanel)UIManager.Instance.PushPanelFromRes(UIPanelName.ispanel, UIManager.CanvasType.Screen, false, false);
                ispanel.SetContent("提示", "本次大版本更新需要下載下傳" + (DataMgr.m_downTotal / 1024d/1024d).ToString("0.00") + "MB資源");
                ispanel.m_cancel = () =>
                {
                    Debug.Log("取消");
#if UNITY_EDITOR
                    EditorApplication.isPlaying = false;
#else
                Application.Quit();
#endif


                };

                while (ispanel.m_isClickOk == false)
                {
                    yield return null;
                }

                yield return StartCoroutine(doDownResources(updateFiles, updateUrls));
            }

            Debug.Log("apk下載下傳完成:"+ dataPath + apkName);
            UIManager.Instance.PopSelf();

            string path = dataPath + apkName;
            path = path.Replace(":", "");
            AndroidFunc.InstallApk(path);

        }
        yield return null;
    }      

資源更新

  1. apk版本号一緻情況下,擷取伺服器cdnfiles.txt檔案
  2. files.txt資訊,每行格式為 ab包 | md5| ab包大小
  3. Unity3d+虛拟城市:更新,登入流程:APK更新,資源更新,注冊登入
  4. 檔案逐行掃描,跟本地檔案對比,本地md5與伺服器不一緻或者缺少本地檔案,把此檔案加入更新清單中
private IEnumerator doUpdateResources()
   {
       Debug.Log("更新資源");
       if (AppConst.m_isUpdateRes == false)
       {
           yield break;
       }
       UIManager.Instance.PushPanelFromRes(UIPanelName.firstpanel, UIManager.CanvasType.Screen);
       //LuaCall("UpdateResourceAPI", "ShowUpdateInfo", UpdateResourcePanelApi, 1, 0);
       Debug.Log("打開了第一個面闆");
       string dataPath = AppConst.AbDataPath  + "/"; //資料目錄
       string url = AppConst.DownUri + "/";

       if (Directory.Exists(AppConst.AbDataPath) == false)
       {
           Directory.CreateDirectory(AppConst.AbDataPath);
       }
       WWW www = new WWW(url + "files.txt");
       Debug.Log("下載下傳的files的url:"+www.url);
       yield return www;
       if (www.error != null)
       {
           Debug.LogError("Update Resources Failed! :" + www.error.ToString());
           //StartGameManager();
           Debug.Log("不能更新,開始遊戲");
           UIManager.Instance.PopSelf();
           yield break;
       }

       List<string> updateUrls = new List<string>();
       List<string> updateFiles = new List<string>();

       File.WriteAllBytes(dataPath + "files.txt", www.bytes);
       string[] files = www.text.Split('\n');
       int needUpdateSize = 0;
       for (int i = 0; i < files.Length; i++)
       {
           var file = files[i];
           if (string.IsNullOrEmpty(file))
               continue;

           string[] keyValue = file.Split('|');
           string filename = keyValue[0];
           string localfile = (dataPath + filename).Trim();
           string path = Path.GetDirectoryName(localfile);
           if (!Directory.Exists(path))
           {
               Directory.CreateDirectory(path);
           }
           string fileUrl = url + filename;
           bool needUpdate = !File.Exists(localfile);
           if (!needUpdate)
           {
               string remoteMd5 = keyValue[1].Trim();
               string localMd5 = PublicFunc.GetFileMD5(localfile);
               needUpdate = !remoteMd5.Equals(localMd5);
           }

           if (needUpdate)
           {
               updateUrls.Add(fileUrl);
               updateFiles.Add(localfile);

               needUpdateSize += int.Parse(keyValue[2]);
           }
       }
       DataMgr.m_downTotal = needUpdateSize * 1024;

       if (DataMgr.m_downTotal > 0)
       {
           Debug.Log("打開了更新确認下載下傳面闆");
           ispanel ispanel = (ispanel)UIManager.Instance.PushPanelFromRes(UIPanelName.ispanel, UIManager.CanvasType.Screen,false,false);
           ispanel.SetContent("提示", "本次更新需要下載下傳" + (DataMgr.m_downTotal / 1024d / 1024d).ToString("0.00") + "MB資源");
           ispanel.m_cancel = () => { Debug.Log("取消");
#if UNITY_EDITOR
               EditorApplication.isPlaying = false;
#else
               Application.Quit();
#endif


           };

           while (ispanel.m_isClickOk == false)
           {
               yield return null;
           }

           yield return StartCoroutine(doDownResources(updateFiles, updateUrls));
       }
       UIManager.Instance.PopSelf();
       //StartGameManager();
   }      

檔案下載下傳器

WebClient下載下傳,實時通知下載下傳進入給主程序

public class FileDownloder : MonoBehaviour {

    public System.Diagnostics.Stopwatch sw;

    public string DownloadingFileName;
    public float DownloadingSpeed;
    public bool DownloadComplete;
    long m_lastDown = 0;
    public FileDownloder()
    {
        sw = new System.Diagnostics.Stopwatch();
        DownloadComplete = false;
        DownloadingFileName = "";
    }

    public bool DownloadFile(string url, string file)
    {
        if (DownloadingFileName == "")
        {
            DownloadComplete = false;
            DownloadingFileName = file;

            Loom.RunAsync(() =>
            {
                using (WebClient client = new WebClient())
                {
                    sw.Start();
                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
                    client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
                    //Debug.Log(String.Format("Download URL:{0} FILE:{1}", url, file));
                    client.DownloadFileAsync(new Uri(url), file);
                }
            });
            return true;
        }
        else
        {
            return false;
        }
    }

    private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        sw.Reset();
        m_lastDown = 0;
        DownloadComplete = true;
        DownloadingFileName = "";
    }

    private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        DataMgr.m_downCur += (e.BytesReceived - m_lastDown);
        m_lastDown = e.BytesReceived;
        DownloadingSpeed = float.Parse((e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));

        Loom.QueueOnMainThread((param) =>
        {
            EventManager.Instance.DispatchEvent(Common.EventStr.UpdateProgress, new EventDataEx<float>(DownloadingSpeed));
        }, null);
        if (e.ProgressPercentage == 100 && e.BytesReceived == e.TotalBytesToReceive)
        {
            sw.Reset();
            m_lastDown = 0;
            DownloadComplete = true;
            DownloadingFileName = "";
        }
    }
}      

讀完資料進入loginpanel

這台手機第一次打開遊戲

  1. 如果第一次打開遊戲,向固定登入http位址,請求到HallServer,ChatServer ip位址端口号,連接配接
  2. 打開注冊視窗,通過SMSSDK短信驗證碼
  3. Unity3d+虛拟城市:更新,登入流程:APK更新,資源更新,注冊登入
  4. 驗證碼通過,發送手機号給HallServer,确定是新使用者還是注冊使用者
  5. 最後得到登陸資訊,發送登陸協定,等回包正式進入遊戲第一個場景

全部源碼下載下傳

示範視訊

繼續閱讀