以编程方式下载和启动应用程序时解析错误

时间:2018-06-28 15:36:18

标签: android xamarin.forms

我正在使用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);

1 个答案:

答案 0 :(得分:0)

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