发布:2021/10/26 8:51:55作者:管理员 来源:本站 浏览次数:982
前言
最近需要做一个android的app。但是我不会java呀,虽然大学时候学过,但是完全还给老师了。于是我就用C#做了一个Android的app。如果有问题请QQ联系1067097173
环境准备
vs2019 iis .netcore3.0 xamarin
iis用来存放发布的apk,最终可以通过http访问下载相关文件 update存放版本号
具体实现
在app程序启动方法中检查当前的版本,然后下载服务器存放的update.txt来对比,然后把apk下载到手机本地,最后更新。
具体代码
public string GetVersion(string url)
{
try
{
WebClient client = new WebClient();
Stream str = client.OpenRead(url);
StreamReader reader = new StreamReader(str);
var value = reader.ReadLine();
return value;
}
catch (System.Exception exp)
{
Toast.MakeText(this, "更新异常:" + exp.Message, ToastLength.Long).Show();
return "";
}
}
[Obsolete]
public void DownFile(string url)
{
//loading = new AlertDialog.Builder(this);
//loading.SetTitle("下载文件");
//loading.SetMessage("更新中...");
//alertDialog = loading.Show();
//progressDialogHandler = new Handler((w) =>
//{
// loading.SetMessage(w.Obj.ToString());
// Toast.MakeText(loading.Context, w.Obj.ToString(), ToastLength.Short).Show();
//});
pg = new ProgressDialog(this);
pg.SetTitle ("文件下载中...");
pg.Max = 100;
pg.SetCancelable(false);
pg.SetProgressStyle(ProgressDialogStyle.Horizontal);
pg.Show();
try
{
//if (Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted))
//{
WebClient client = new WebClient();
client.DownloadFileCompleted += client_DownloadFileCompleted;
client.DownloadProgressChanged += client_DownloadProgressChanged;
var backingFile = System.IO.Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, "count.txt");
var saveFolder = Android.OS.Environment.ExternalStorageDirectory;
//var saveFolder = Android.OS.Environment.DataDirectory;
//if (!Android.OS.fie System.IO.Directory.Exists(saveFolder)) System.IO.Directory.CreateDirectory(saveFolder);
var file = string.Format("{0}/{1}{2}", saveFolder, this.PackageName, ".apk");// fileName + "appName" + versionName + ext;
file = string.Format("{0}/{1}{2}", Xamarin.Essentials.FileSystem.AppDataDirectory, this.PackageName, ".apk");
if (System.IO.Directory.Exists(Xamarin.Essentials.FileSystem.AppDataDirectory)) {
}
using (var fs = new FileStream(file, FileMode.Create))
{
}
client.DownloadFileAsync(new Uri(url), file);
//}
}
catch (System.Exception exp)
{
Toast.MakeText(this, "更新异常:" + exp.Message, ToastLength.Long).Show();
;
}
}
private void OpenUpDialog(string sourcever, string updatever)
{
builder = new AlertDialog.Builder(this);
builder.SetTitle("有新版本!!!").SetMessage(string.Format("当前:{0} 新版本:{1}", sourcever, updatever)).SetNeutralButton("暂不更新",
(s, e) => {
var UserNO = ReadData2("UserNO");
var Userid = ReadData2("Userid");
var password = ReadData2("Password");
var username = ReadData2("UserName");
if (JudgeLoginFunction(UserNO, password))
{
Intent intent = new Intent(this, typeof(WebTestActivity));
intent.PutExtra("UserNO", UserNO);
intent.PutExtra("Userid", Userid);
intent.PutExtra("UserName", username);
StartActivity(intent);
}
}).SetPositiveButton("立即更新", (s, e) =>
{
DownFile(pathdir + "/" + this.PackageName + ".apk");
}).Show();
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.UserState == null)
{
//this.lblMessage.Text = e.UserState.ToString() + ",下载完成";
Intent i = new Intent(Intent.ActionView);
var saveFolder = Android.OS.Environment.ExternalStorageDirectory;
//if (!Android.OS.fie System.IO.Directory.Exists(saveFolder)) System.IO.Directory.CreateDirectory(saveFolder);
var file = string.Format("{0}/{1}{2}", saveFolder, this.PackageName, ".apk");// fileName + "appName" +
//i.SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(file)), "application/vnd.android.package-archive");
//i.SetFlags(ActivityFlags.NewTask);
file = string.Format("{0}/{1}{2}", Xamarin.Essentials.FileSystem.AppDataDirectory, this.PackageName, ".apk");
//StartActivity(i);
Java.IO.File apkFile = new Java.IO.File(file);
Intent intent = new Intent(Intent.ActionView);
intent.SetFlags(ActivityFlags.NewTask);
if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
{
intent.SetFlags(ActivityFlags.GrantReadUriPermission);
Android.Net.Uri uri = FileProvider.GetUriForFile(this, PackageName + ".fileprovider", apkFile);
intent.SetDataAndType(uri, "application/vnd.android.package-archive");
}
else
{
intent.SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(file)), "application/vnd.android.package-archive");
}
StartActivity(intent);
}
if (e.Error != null)
{
Toast.MakeText(this, "更新异常:" + e.Error.Message, ToastLength.Long).Show();
}
pg.Dismiss();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//this.proBarDownLoad.Minimum = 0;
//this.proBarDownLoad.Maximum = (int)e.TotalBytesToReceive;
//this.proBarDownLoad.Value = (int)e.BytesReceived;
//this.lblPercent.Text = e.ProgressPercentage + "%";
//pg.Max = (int)e.TotalBytesToReceive;
pg.Progress = e.ProgressPercentage;
//progressDialogHandler.SendMessage(new Message() { Obj= "更新中..."+ e.ProgressPercentage + "%" });
}
注意问题
1 iis部署时候 MIME类型一定要设置为”application/vnd.android.package-archive“,不然当手机下载完成后不会自动提示安装
2 由于android版本权限控制问题,下载存放的地方最好不要放的外部存储,会报权限不足,
3 高版本的android需要用fileprovider方式安装