android - 以编程方式下载和启动应用程序时解析错误
问题描述
我正在使用 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);
解决方案
当我为我们的应用程序实现 AutoUpdater 时,我遇到了类似的问题。在我的情况下,问题的根源是我只是忘记刷新完成后正在写入文件的文件流。
推荐阅读
- javascript - 如何不可变地插入排序数组?
- windows - Vagrant 如何通过 SSH 从 Windows 命令获取退出代码?
- c++ - 一个线程写入的值是否可以保证在不锁定该变量的情况下被另一个线程看到?
- html - 教授表示我错过了 2 个标签样式,但不知道是什么
- tensorflow - 张量流分布式训练的问题(提前停止)
- azure - 如何验证令牌
- sql - 将 SQL 语句作为记录值插入 PostgreSQL 列
- python - 如何将用户输入限制为两个可能的字符串?
- json - 如何在 Play 2.7 for Scala 中编写一个通用的 JSON 解析器来验证入站请求?
- ascii - 数据流中数据块之间的标准分隔符?