/// <summary> /// 安装APK文件 /// </summary> /// <param name="activity"></param> /// <param name="filename"></param> /// <param name="dialog"></param> private static void Down(Activity activity, File file, Dialog dialog) { var context = Application.Context; if (!file.Exists()) { return; } else { //通过在代码中写入linux指令修改此apk文件的权限,改为全局可读可写可执行 String[] command = { "chmod", "777", file.Path }; Java.Lang.ProcessBuilder builder = new Java.Lang.ProcessBuilder(command); try { builder.Start(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } } Uri uri; var intent = new Intent(Intent.ActionView); if (Build.VERSION.SdkInt >= BuildVersionCodes.N) { uri = FileProvider.GetUriForFile(context, "com.jshcrb.MyCensus.fileprovider", file); intent.SetAction(Intent.ActionInstallPackage); intent.SetDataAndType(uri, "application/vnd.android.package-archive"); intent.SetFlags(ActivityFlags.NewTask); //FLAG_GRANT_URI_PERMISSION intent.AddFlags(ActivityFlags.GrantPersistableUriPermission); intent.AddFlags(ActivityFlags.GrantPrefixUriPermission); intent.AddFlags(ActivityFlags.GrantWriteUriPermission); intent.AddFlags(ActivityFlags.GrantReadUriPermission); context.StartActivity(intent); } else { uri = Uri.FromFile(file); //intent.SetDataAndType(Android.Net.Uri.Parse("file://" + filePath), "application/vnd.android.package-archive"); intent.SetDataAndType(uri, "application/vnd.android.package-archive"); intent.SetFlags(ActivityFlags.NewTask); context.StartActivity(intent); } activity.RunOnUiThread(() => { dialog.Hide(); dialog.Dismiss(); dialog.Cancel(); }); }
string getOSCommandOutput(string[] args) { Java.Lang.ProcessBuilder pb = new Java.Lang.ProcessBuilder(args); Java.Lang.Process process = pb.Start(); if (process.InputStream != null) { using (StreamReader reader = new StreamReader(process.InputStream)) { return(reader.ReadToEnd()); } } return(null); }
public async Task Ping(string host, CancellationToken token, IProgress <string> progress, int count = 0) { try { var stopwatch = Stopwatch.StartNew(); Java.Lang.Process process = null; if ((long)Build.VERSION.SdkInt <= 16) { // shiny APIS process = Java.Lang.Runtime.GetRuntime().Exec(string.Format("/system/bin/ping -w 1 -c 1 {0}", host)); } else { process = new Java.Lang.ProcessBuilder(). Command("/system/bin/ping", host).RedirectErrorStream(true).Start(); } using (var reader = new StreamReader(process.InputStream)) { var n = 0; do { var result = await reader.ReadLineAsync(); if (result != null) { Log.Info(this.ToString(), result); progress.Report(result); } else { await Task.Delay(10); } } while (!token.IsCancellationRequested && (count <= 0 || n++ < count)); } process.Destroy(); } catch (IOException e) { Log.Error(this.ToString(), e.Message); progress.Report(e.Message); } }
public async Task <bool> IsHostReachable(string host, TimeSpan timeout) { bool reachable = false; try { var stopwatch = Stopwatch.StartNew(); Java.Lang.Process process = null; if ((long)Build.VERSION.SdkInt <= 16) { // shiny APIS process = Java.Lang.Runtime.GetRuntime().Exec(string.Format("/system/bin/ping -w 1 -c 1 {0}", host)); } else { process = new Java.Lang.ProcessBuilder(). Command("/system/bin/ping", host).RedirectErrorStream(true).Start(); } using (var reader = new StreamReader(process.InputStream)) { do { var result = await reader.ReadLineAsync(); Log.Info(this.ToString(), result); } while (!reachable && stopwatch.ElapsedMilliseconds < timeout.TotalMilliseconds); } process.Destroy(); reachable = true; } catch (IOException e) { Log.Error(this.ToString(), e.Message); reachable = false; } return(reachable); }
public async Task<bool> IsHostReachable(string host, TimeSpan timeout) { bool reachable = false; try { var stopwatch = Stopwatch.StartNew(); Java.Lang.Process process = null; if ((long)Build.VERSION.SdkInt <= 16) { // shiny APIS process = Java.Lang.Runtime.GetRuntime().Exec(string.Format("/system/bin/ping -w 1 -c 1 {0}", host)); } else { process = new Java.Lang.ProcessBuilder(). Command("/system/bin/ping", host).RedirectErrorStream(true).Start(); } using (var reader = new StreamReader(process.InputStream)) { do { var result = await reader.ReadLineAsync(); Log.Info(this.ToString(), result); } while (!reachable && stopwatch.ElapsedMilliseconds < timeout.TotalMilliseconds); } process.Destroy(); reachable = true; } catch (IOException e) { Log.Error(this.ToString(), e.Message); reachable = false; } return reachable; }
public void OpenFile(byte[] data, string name) { string directory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); string path = Path.Combine(directory, name); foreach (string file in Directory.GetFiles(directory)) { if (Path.GetExtension(file) == ".apk") { File.Delete(file); } } File.WriteAllBytes(path, data); Intent intent = new Intent(Intent.ActionView); Android.Net.Uri fileUri = null; if (Build.VERSION.SdkInt <= BuildVersionCodes.N || Build.VERSION.SdkInt >= BuildVersionCodes.O) { string[] command = { "chmod", "777", path }; Java.Lang.ProcessBuilder builder = new Java.Lang.ProcessBuilder(command); try { builder.Start(); } catch (IOException e) { } fileUri = Android.Net.Uri.FromFile(new Java.IO.File(path)); intent.SetFlags(ActivityFlags.NewTask); } else { fileUri = FileProvider.GetUriForFile(Application.Context, "CloudMusic.CloudMusic", new Java.IO.File(path)); intent.SetFlags(ActivityFlags.GrantReadUriPermission); } intent.SetDataAndType(fileUri, "application/vnd.android.package-archive"); Application.Context.StartActivity(intent); }
/// <summary> /// 下载更新并安装 /// </summary> /// <param name="activity"></param> /// <param name="updateInfo"></param> private void DownloadFileV2(Activity activity, IProgressDialog pDialog, UpdateInfo updateInfo) { try { //string directory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); //完整的最新应用程序文件名 string flaName; bool downloadedOK = false; //判断文件目录是否存在 //== Download/apk/ // "/storage/emulated/0/Android/data/com.dcms.clientv3/files/Download/apk" // "/storage/emulated/0/Android/data/com.dcms.clientv3/files/Download" using (var tempFile = new File(Application.Context.GetExternalFilesDir(Environment.DirectoryDownloads), "apk")) { if (!tempFile.Exists()) { //创建目录 try { tempFile.Mkdir(); } catch (Exception e) { e.PrintStackTrace(); } } flaName = tempFile.Path + "/" + updateInfo.Version + ".apk"; } //外部存储路径下的apk文件 File file = new File(flaName); //防止文件过多 if (file.Exists()) { try { file.Delete(); } catch (Exception ex) { ex.PrintStackTrace(); } } //默认:http://storage.jsdcms.com:5000/api/version/updater/app/download using (var webClient = new WebClient()) { //进度 webClient.DownloadProgressChanged += (s, e) => { var bytesIn = double.Parse(e.BytesReceived.ToString()); var totalBytes = double.Parse(e.TotalBytesToReceive.ToString()); if (totalBytes == 0) { totalBytes = 1; } var percentage = (int)(bytesIn / totalBytes * 100); if (percentage == 100) { downloadedOK = true; } activity.RunOnUiThread(() => { if (pDialog != null) { pDialog.PercentComplete = percentage; } }); }; //完成 webClient.DownloadDataCompleted += (s, e) => { activity.RunOnUiThread(() => { try { //关闭ProgressDialog if (pDialog != null) { pDialog.Hide(); } //写入流 if (e.Result.Length > 0 && e.Error == null && e.Cancelled == false) { byte[] buffer = e.Result; using (var sfs = new FileStream(flaName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { using (MemoryStream ms = new MemoryStream(buffer)) { ms.CopyTo(sfs); } } } //外部存储路径下的apk文件 if (!file.Exists()) { return; } else { //通过在代码中写入linux指令修改此apk文件的权限,改为全局可读可写可执行 string[] command = { "chmod", "777", file.Path }; Java.Lang.ProcessBuilder builder = new Java.Lang.ProcessBuilder(command); try { builder.Start(); } catch (Java.IO.IOException ex) { ex.PrintStackTrace(); } } //是否下载 if (downloadedOK) { var context = Application.Context; Uri uri; try { //安装 var installApk = new Intent(Intent.ActionView); installApk.SetFlags(ActivityFlags.NewTask); if (Build.VERSION.SdkInt >= BuildVersionCodes.N) { uri = FileProvider.GetUriForFile(context, AutoUpdate.Authority, file); //Intent.ActionInstallPackage installApk.SetAction("android.intent.action.INSTALL_PACKAGE"); installApk.SetDataAndType(uri, "application/vnd.android.package-archive"); installApk.AddFlags(ActivityFlags.GrantPersistableUriPermission); installApk.AddFlags(ActivityFlags.GrantPrefixUriPermission); installApk.AddFlags(ActivityFlags.GrantWriteUriPermission); installApk.AddFlags(ActivityFlags.GrantReadUriPermission); } else { uri = Uri.FromFile(file); installApk.SetDataAndType(uri, "application/vnd.android.package-archive"); } context.StartActivity(installApk); } catch (ActivityNotFoundException) { var errorInstalled = new AlertDialog.Builder(context).Create(); errorInstalled.SetTitle("出了点问题"); errorInstalled.SetMessage(string.Format("{0} 不能被安装,请重试", "Wesley " + updateInfo.Version)); errorInstalled.Show(); } downloadedOK = false; } else { try { //删除 System.IO.File.Delete(flaName); } catch (ActivityNotFoundException ex) { ex.PrintStackTrace(); } } } catch (TargetInvocationException) { } catch (WebException) { } catch (Exception) { } finally { if (file != null) { file.Dispose(); } } }); }; //开始异步下载 //application/octet-stream webClient.DownloadDataAsync(new System.Uri(updateInfo.DownLoadUrl), flaName); }; } catch (System.Net.Sockets.SocketException ex) { } catch (Exception ex) { } }
public async Task Ping(string host, CancellationToken token, IProgress<string> progress, int count = 0) { try { var stopwatch = Stopwatch.StartNew(); Java.Lang.Process process = null; if ((long)Build.VERSION.SdkInt <= 16) { // shiny APIS process = Java.Lang.Runtime.GetRuntime().Exec(string.Format("/system/bin/ping -w 1 -c 1 {0}", host)); } else { process = new Java.Lang.ProcessBuilder(). Command("/system/bin/ping", host).RedirectErrorStream(true).Start(); } using (var reader = new StreamReader(process.InputStream)) { var n = 0; do { var result = await reader.ReadLineAsync(); if (result != null) { Log.Info(this.ToString(), result); progress.Report(result); } else { await Task.Delay(10); } } while (!token.IsCancellationRequested && (count <= 0 || n++ < count)); } process.Destroy(); } catch (IOException e) { Log.Error(this.ToString(), e.Message); progress.Report(e.Message); } }