xamarin.forms 版本自動更新(針對android)

原文: xamarin.forms 版本自動更新(針對android)

1.首先同過url地址下載文件,這裏必需要啓用單獨一個下載線程html

 new Thread(run).Start();android

經過url下載的方法app

 public void run()
        {
            int receivedBytes = 0;
            int totalBytes = 0;
            string dirPath = "/sdcard/updateVersion/version";
            var filePath = Path.Combine(dirPath, "hz_android.apk");
            URL url = new URL(urlToDownload);//urlToDownload 下載文件的url地址post

            HttpURLConnection conn = (HttpURLConnection)url.OpenConnection();
            conn.Connect();
            Stream Ins = conn.InputStream;
            totalBytes = conn.ContentLength;
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            else
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
            using (FileStream fos = new FileStream(filePath, FileMode.Create))
            {
                byte[] buf = new byte[512];url

                do
                {
                    int numread = Ins.Read(buf, 0, 512);
                    receivedBytes += numread;
                    if (numread <= 0)
                    {
                        break;
                    }
                    fos.Write(buf, 0, numread);線程

//進度條代碼
                    if (progessReporter != null)
                    {
                        DownloadBytesProgress args = new DownloadBytesProgress(urlToDownload, receivedBytes, totalBytes);
                        progessReporter.Report(args);
                    }
                } while (true);
            }orm

//調用下載的文件進行安裝
            installApk(filePath);
        }htm

 

 private void installApk(string filePath)
        {
            var context = Forms.Context;
            if (context == null)
                return;
            // 經過Intent安裝APK文件
            Intent intent = new Intent(Intent.ActionView);
            intent.SetDataAndType(Uri.Parse("file://" + filePath), "application/vnd.android.package-archive");
            //Uri content_url = Uri.Parse(filePath);
            //intent.SetData(content_url);
            intent.SetFlags(ActivityFlags.NewTask);
            context.StartActivity(intent);
        }blog

相關文章
相關標籤/搜索