1.首先同過url位址下載下傳檔案,這裡必須要啟用單獨一個下載下傳線程
new Thread(run).Start();
通過url下載下傳的方法
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位址
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];
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);
//調用下載下傳的檔案進行安裝
installApk(filePath);
}
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);