首页 > 解决方案 > 以编程方式下载和启动应用程序时解析错误

问题描述

我正在使用 Xamarin Forms 并且一直在尝试让我的应用程序自动更新。这是一个不通过商店的私人应用程序,只有.apk被操纵。

.apk当有更新的版本可用时,我正在下载并以编程方式启动它。下载似乎进行得很好,但是在启动下载的时候.apk,我得到一个解析错误。

        try
        {          
            this.OnEnded += Download_OnEnded;

            string uri = string.Format("setupFilesAndroid/{0}/{1}", this.distantVersion, App.CommonDatas.ANDROID_INSTALLER_NAME);

            //Prepare the client for the download
            HttpClient client = new HttpClient()
            {
                BaseAddress = new Uri(this.baseUri)
            };
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Add("Computer-id", CrossDeviceInfo.Current.Id);

            //Create or get the right folder and file to download to
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            IFolder appFolder = await rootFolder.CreateFolderAsync("App", CreationCollisionOption.OpenIfExists);

            IFile file = await appFolder.CreateFileAsync("app.apk", CreationCollisionOption.ReplaceExisting);

            //Download the file
            using (var fileHandler = await file.OpenAsync(FileAccess.ReadAndWrite))
            {
                var httpResponse = await client.GetAsync(uri);
                byte[] dataBuffer = await httpResponse.Content.ReadAsByteArrayAsync();

                await fileHandler.WriteAsync(dataBuffer, 0, dataBuffer.Length);
            }

            if (this.OnEnded != null)
            {
                this.OnEnded(this, null);
            }
        }
        catch {}

以及事件调用的方法OnEnded

    //throws an error if the file doesn't exists
    //this works fine so I guess the file is in fact downloaded
        try
        {
            IFolder folder = await FileSystem.Current.LocalStorage.GetFolderAsync("App");
            IFile file = await folder.GetFileAsync("app.apk");
        }
        catch
        {}

        //Use of Dependency service for launching the downloaded app
        IDownloadManager native = DependencyService.Get<IUpdateManager>();
        native.RunUpdate();

这是RunUpdate()方法:

        IFolder folder = await FileSystem.Current.LocalStorage.GetFolderAsync("App");
        IFile file = await folder.GetFileAsync("app.apk");

        Intent promptInstall = new Intent(Intent.ActionView).SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(file.Path)), "application/vnd.android.package-archive");
        promptInstall.AddFlags(ActivityFlags.NewTask);

        Forms.Context.StartActivity(promptInstall);

有什么帮助吗?或者至少是关于如何调试的指针?

编辑:手动下载和安装更新时工作正常。我找不到检查以编程方式下载的文件的方法,因为它已下载到无法访问的路径(类似于/data/user/0/...)。

Edit2:经过更多测试,下载的文件很好并且能够完全重新安装应用程序,因此错误很可能发生在Forms.Context.StartActivity(promptInstall);

标签: androidxamarin.forms

解决方案


当我为我们的应用程序实现 AutoUpdater 时,我遇到了类似的问题。在我的情况下,问题的根源是我只是忘记刷新完成后正在写入文件的文件流。


推荐阅读