public override void OnReceive(Context context, Intent intent) { try { if (intent.Action == DownloadManager.ActionDownloadComplete) { if (ActivityContext == null) { return; } DownloadManager downloadManagerExcuter = (DownloadManager)Application.Context.GetSystemService(Context.DownloadService); long downloadId = intent.GetLongExtra(DownloadManager.ExtraDownloadId, -1); DownloadManager.Query query = new DownloadManager.Query(); query.SetFilterById(downloadId); ICursor c = downloadManagerExcuter.InvokeQuery(query); var sqlEntity = new SqLiteDatabase(); if (c.MoveToFirst()) { int columnIndex = c.GetColumnIndex(DownloadManager.ColumnStatus); if (c.GetInt(columnIndex) == (int)DownloadStatus.Successful) { string downloadedPath = c.GetString(c.GetColumnIndex(DownloadManager.ColumnLocalUri)); ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo(); ActivityManager.GetMyMemoryState(appProcessInfo); if (appProcessInfo.Importance == Importance.Foreground || appProcessInfo.Importance == Importance.Background) { sqlEntity.InsertOrUpdate_LatestDownloadsSound(Sound.Id, downloadedPath); if (TypeActivity == "Main") { if (ActivityContext is HomeActivity tabbedMain) { tabbedMain.SoundController.BtnIconDownload.Tag = "Downloaded"; tabbedMain.SoundController.BtnIconDownload.SetImageResource(Resource.Drawable.ic_check_circle); tabbedMain.SoundController.BtnIconDownload.SetColorFilter(Color.Red); tabbedMain.SoundController.ProgressBarDownload.Visibility = ViewStates.Invisible; tabbedMain.SoundController.BtnIconDownload.Visibility = ViewStates.Visible; tabbedMain.LibrarySynchronizer.AddToLatestDownloads(Sound); } } } else { sqlEntity.InsertOrUpdate_LatestDownloadsSound(Sound.Id, downloadedPath); } } } sqlEntity.Dispose(); } } catch (Exception exception) { Console.WriteLine(exception); } }
public override void OnReceive(Context context, Intent intent) { try { if (intent.Action == DownloadManager.ActionDownloadComplete) { DownloadManager downloadManagerExcuter = (DownloadManager)Application.Context.GetSystemService(Context.DownloadService); long downloadId = intent.GetLongExtra(DownloadManager.ExtraDownloadId, -1); DownloadManager.Query query = new DownloadManager.Query(); query.SetFilterById(downloadId); ICursor c = downloadManagerExcuter.InvokeQuery(query); if (c.MoveToFirst()) { SqLiteDatabase dbDatabase = new SqLiteDatabase(); int columnIndex = c.GetColumnIndex(DownloadManager.ColumnStatus); if (c.GetInt(columnIndex) == (int)DownloadStatus.Successful) { string downloadedPath = c.GetString(c.GetColumnIndex(DownloadManager.ColumnLocalUri)); ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo(); ActivityManager.GetMyMemoryState(appProcessInfo); if (appProcessInfo.Importance == Importance.Foreground || appProcessInfo.Importance == Importance.Background) { dbDatabase.Update_WatchOfflineVideos(Video.id, downloadedPath); var videoViewer = ContextActivty as Video_Viewer_Activity; var fullScreen = ContextActivty as FullScreenVideoActivity; if (videoViewer != null) { if (videoViewer.VideoActionsController.Videodata.id == Video.id) { videoViewer.VideoActionsController.Download_icon.SetImageDrawable(Application.Context.GetDrawable(Resource.Drawable.ic_checked_red)); videoViewer.VideoActionsController.Download_icon.Tag = "Downloaded"; } } else if (fullScreen != null) { if (fullScreen.VideoActionsController.Videodata.id == Video.id) { fullScreen.VideoActionsController.Download_icon.SetImageDrawable(Application.Context.GetDrawable(Resource.Drawable.ic_checked_red)); fullScreen.VideoActionsController.Download_icon.Tag = "Downloaded"; } } } else { dbDatabase.Update_WatchOfflineVideos(Video.id, downloadedPath); } } dbDatabase.Dispose(); } } } catch (Exception exception) { Crashes.TrackError(exception); } }
public override void OnReceive(Context context, Intent intent) { var action = intent.Action; if (DownloadManager.ActionDownloadComplete.Equals(action)) { var downloadId = intent.GetLongExtra(DownloadManager.ExtraDownloadId, 0); var query = new DownloadManager.Query(); query.SetFilterById(_webViewClient.Enqueue); var c = _webViewClient.Dm.InvokeQuery(query); if (c.MoveToFirst()) { var columnIndex = c.GetColumnIndex(DownloadManager.ColumnStatus); if ((int) Android.App.DownloadStatus.Successful == c.GetInt(columnIndex)) { var view = (ImageView) _webViewClient.Controls.Activity.FindViewById(12); var uriString = c.GetString(c.GetColumnIndex(DownloadManager.ColumnLocalUri)); view.SetImageURI(Android.Net.Uri.Parse(uriString)); } var list = new List<string>(); var columnNames = c.GetColumnNames(); for (var i = 0; i < c.ColumnCount; i++) { list.Add(columnNames[i]); } columnIndex = c.GetColumnIndex(DownloadManager.ColumnReason); var s = c.GetString(columnIndex); _webViewClient.Controls.Title.Text = s; } } }
private void Action(Context context, Intent intent) { DownloadManager.Query query = new DownloadManager.Query(); long id = intent.GetLongExtra(DownloadManager.ExtraDownloadId, 0); query.SetFilterById(id); var c = downloadManager.InvokeQuery(query); if (c.MoveToFirst()) { var filename = c.GetString(c.GetColumnIndex(DownloadManager.ColumnLocalUri)); // var path = Path.Combine(pathx.AbsolutePath, "com.chuanda.drivermobile.apk"); var xxxxx = Java.Net.URI.Create(filename); var mApkFile = new Java.IO.File(Java.Net.URI.Create(filename)); if (mApkFile.Exists()) { InstallApp(mApkFile, context); } } }
public override void OnReceive(Context context, Intent intent) { long id = intent.GetLongExtra(DownloadManager.ExtraDownloadId, -1); System.Console.WriteLine(string.Format("Received intent for {0}:\n", id)); if (DownloadManager.ActionDownloadComplete.Equals(intent.Action)) { if (downloadId == id) { var manager = DownloadManager.FromContext(context); var query = new DownloadManager.Query(); query.SetFilterById(id); ICursor cursor = manager.InvokeQuery(query); if (cursor.MoveToFirst()) { // get the status var columnIndex = cursor.GetColumnIndex(DownloadManager.ColumnStatus); var status = (DownloadStatus)cursor.GetInt(columnIndex); System.Console.WriteLine(string.Format(" Received status {0}\n", status)); if (status == Android.App.DownloadStatus.Successful) { DownloadCompleted?.Invoke(); } } } } }
private DownloadState GetDownloadState(string id) { var longId = long.Parse(id); var manager = (DownloadManager)Application.Context.GetSystemService(Context.DownloadService); var query = new DownloadManager.Query(); query.SetFilterById(longId); using var cursor = manager.InvokeQuery(query); if (cursor.MoveToFirst()) { int status = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnStatus)); int reason = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnReason)); string downloadLocation = cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnLocalUri)); long totalSize = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnTotalSizeBytes)); long downloaded = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnBytesDownloadedSoFar)); cursor.Close(); return(new DownloadState(CreateDownloadStatus(status), CreateReason(reason), downloadLocation == null ? null : new Uri(downloadLocation), totalSize, downloaded)); } return(null); }
/// <summary> /// Get the status of the download /// </summary> /// <returns>The download state</returns> public InstallAbility GetDownloadState() { InstallAbility installAbility = InstallAbility.UpdateNotFound; if (this.HasDownloadReference) { var query = new DownloadManager.Query(); query.SetFilterById(this.downloadReference); var cursor = this.downloadManager.InvokeQuery(query); if (cursor.MoveToFirst()) { var status = (DownloadStatus)cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnStatus)); switch (status) { case DownloadStatus.Successful: installAbility = InstallAbility.ReadyToInstall; break; case DownloadStatus.Paused: case DownloadStatus.Pending: case DownloadStatus.Running: installAbility = InstallAbility.Downloading; break; case DownloadStatus.Failed: var reasonCode = (DownloadError)cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnReason)); if (reasonCode == DownloadError.InsufficientSpace || reasonCode == DownloadError.FileError || reasonCode == DownloadError.DeviceNotFound) { installAbility = InstallAbility.UnableToStoreOnDevice; } else if (reasonCode == DownloadError.FileAlreadyExists) { installAbility = InstallAbility.ReadyToInstall; } else if ((int)reasonCode == 404) { installAbility = InstallAbility.UpdateNotFound; } else { installAbility = InstallAbility.DownloadFailed; } break; } } } return(installAbility); }
public override void OnReceive(Android.Content.Context context, Intent intent) { DownloadManager.Query query = new DownloadManager.Query(); long id = _helper.downloadId; query.SetFilterById(id); query.SetFilterByStatus(DownloadStatus.Successful); ICursor cursor = _helper.downloadManager.InvokeQuery(query); if (cursor.MoveToFirst()) { _helper.DoneDownloading(); } }
private void MonitorStatus() { var statusQuery = new DownloadManager.Query(); statusQuery.SetFilterById(downloadId); var status = GetStatus(statusQuery); while (!status.Finished) { Thread.Sleep(500); status = GetStatus(statusQuery); OnStatusUpdate(status); } }
/// <summary> /// Gets the install path from the download manager /// </summary> /// <returns>The install path</returns> private string GetInstallPath() { if (this.HasDownloadReference) { var query = new DownloadManager.Query(); query.SetFilterById(this.downloadReference); var cursor = this.downloadManager.InvokeQuery(query); if (cursor.MoveToFirst()) { return(cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnLocalUri))); } } return(string.Empty); }
/// <summary> /// Queries the download status. /// </summary> /// <returns>The download status.</returns> static int QueryDownloadStatus() { var result = -1; DownloadManager.Query query = new DownloadManager.Query().SetFilterById(_downloadID); var cursor = downloadManager.InvokeQuery(query); if (cursor != null) { if (cursor.MoveToFirst()) { result = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnStatus)); } cursor.Close(); } return(result); }
public override void OnReceive(Context context, Intent intent) { var receivedDownloadId = intent.GetLongExtra(DownloadManager.ExtraDownloadId, 0L); if (receivedDownloadId != this.downloadId) { return; } var downloadManager = (DownloadManager)context.GetSystemService(Context.DownloadService); var query = new DownloadManager.Query(); query.SetFilterById(receivedDownloadId); var cursor = downloadManager.InvokeQuery(query); try { if (cursor.MoveToFirst()) { var statusIndex = cursor.GetColumnIndex(DownloadManager.ColumnStatus); if (cursor.GetInt(statusIndex) == (int)DownloadStatus.Successful) { this.completeAction.Invoke(ResultState.Success); } else { var reason = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnReason)); this.userInteraction.Toast(AppResources.DownloadingError.FormatWith(reason), ToastTime.Medium); this.completeAction.Invoke(ResultState.Error); } } else { // The download does not exist anymore this.completeAction.Invoke(ResultState.Error); } } finally { context.UnregisterReceiver(this); } }
private DownloadStatusUpdate GetStatus(DownloadManager.Query statusQuery) { using (var cursor = downloadManager.InvokeQuery(statusQuery)) { if (!cursor.MoveToNext()) { return(new DownloadStatusUpdate("In progress", 0)); } var status = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnStatus)); var reason = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnReason)); var bytesDownloaded = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnBytesDownloadedSoFar)); var totalBytes = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnTotalSizeBytes)); var percentDone = bytesDownloaded / (double)totalBytes; var downloadStatus = (DownloadStatus)status; cursor.Close(); switch (downloadStatus) { case DownloadStatus.Failed: return(CreateFailureUpdate(reason)); case DownloadStatus.Pending: case DownloadStatus.Running: return(new DownloadStatusUpdate("In progress", percentDone)); case DownloadStatus.Paused: Console.WriteLine("REASON IS...: " + reason); return(new DownloadStatusUpdate("Waiting for network", percentDone, paused: true)); case DownloadStatus.Successful: return(new DownloadStatusUpdate("Download Complete", 100)); default: throw new System.Exception("Status not handled " + status); } } }
protected override void onCreate(Bundle savedInstanceState) { var file1 = "http://a.tumblr.com/tumblr_m8ueqqpyyy1rs64dko1.mp3"; var name1 = "E43 Understanding the Dangers of Ego-Depletion by Tim"; base.onCreate(savedInstanceState); var downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE); var preferenceManager = PreferenceManager.getDefaultSharedPreferences(this); var sv = new ScrollView(this); var ll = new LinearLayout(this); //ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll); var b = new android.widget.Button(this).AttachTo(ll); downloadReceiver = new MyDownloadReceiver { }; // O:\src\AndroidDownloadManagerActivity\Activities\ApplicationActivity___c__DisplayClass2___c__DisplayClass4.java:60: cannot find symbol //symbol : class Button //location: class AndroidDownloadManagerActivity.Activities.ApplicationActivity___c__DisplayClass2___c__DisplayClass4 // ViewExtensions.<Button>WithText(this.CS___8__locals3.b, "Download " + this.CS___8__locals3.name1); // ^ b.WithText("Download " + name1); b.AtClick( v => { b.setText("Downloading..."); b.setEnabled(false); var downloadUri = android.net.Uri.parse(file1); // http://developer.android.com/reference/android/app/DownloadManager.Request.html var request = new DownloadManager.Request(downloadUri); request.setTitle("idea-remixer"); request.setDescription(name1); // W/DownloadManager(15222): Aborting request for download 166: while trying to execute request: // java.net.UnknownHostException: Unable to resolve host "a.tumblr.com": // No address associated with hostname var id = downloadManager.enqueue(request); Toast.makeText(this, new { id, downloadUri }.ToString(), Toast.LENGTH_LONG).show(); //Save the request id //var PrefEdit = preferenceManager.edit(); //PrefEdit.putLong(strPref_Download_ID, id); //PrefEdit.commit(); downloadReceiver.AtReceive = delegate { DownloadManager.Query query = new DownloadManager.Query(); //query.setFilterById(preferenceManager.getLong(strPref_Download_ID, 0)); // http://developer.android.com/reference/android/app/DownloadManager.Query.html#setFilterById(long...) query.setFilterById(new[] { id }); Cursor cursor = downloadManager.query(query); if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS); int status = cursor.getInt(columnIndex); if (status == DownloadManager.STATUS_FAILED) { Toast.makeText(this, new { id, status }.ToString(), Toast.LENGTH_LONG).show(); b.WithText("(failed) Download " + name1); b.setEnabled(true); } else if (status == DownloadManager.STATUS_SUCCESSFUL) { //Retrieve the saved request id //long downloadID = preferenceManager.getLong(strPref_Download_ID, 0); var uri = downloadManager.getUriForDownloadedFile(id); Toast.makeText(this, new { id, uri }.ToString(), Toast.LENGTH_LONG).show(); // jsc ignores this type in import? Button __ref0; b.WithText("Download " + name1); b.setEnabled(true); //ParcelFileDescriptor file; //try //{ // file = downloadManager.openDownloadedFile(downloadID); // //FileInputStream fileInputStream = new ParcelFileDescriptor.AutoCloseInputStream(file); // //Bitmap bm = BitmapFactory.decodeStream(fileInputStream); // //image.setImageBitmap(bm); //} //catch // (FileNotFoundException e) //{ // TODO Auto-generated catch block // //e.printStackTrace(); // throw; //} } } }; } ); this.setContentView(sv); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.AutoUpdateLayout); progressBar = FindViewById <ProgressBar>(Resource.Id.progressBar1); textView1 = FindViewById <TextView>(Resource.Id.textView1); progressBar.Max = 100; textView1.Text = "0 %"; FileDelete(); var manager = DownloadManager.FromContext(this); //var manager = (DownloadManager)GetSystemService(Context.DownloadService); var url = new System.Uri(string.Format(@"{0}{1}", GlobalSetting.Instance.MOBILEEndpoint.ToString(), string.Format("{0}{1}{2}", "/", Application.Context.PackageName, ".apk"))); var request = new DownloadManager.Request(Android.Net.Uri.Parse(url.ToString())); request.SetMimeType("application/vnd.android.package-archive"); request.SetTitle("App Download"); request.SetDescription("File Downloading..."); request.SetAllowedNetworkTypes(DownloadNetwork.Wifi | DownloadNetwork.Mobile); request.SetNotificationVisibility(DownloadVisibility.Visible); request.SetAllowedOverMetered(true); //모바일 네트쿼크 request.SetAllowedOverRoaming(true); //로밍 Java.IO.File path = this.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads); request.SetDestinationUri(Android.Net.Uri.FromFile(new Java.IO.File(path, string.Format("{0}{1}", Application.Context.PackageName, ".apk")))); downloadId = manager.Enqueue(request); Task.Run(() => { for (; ;) { var query = new DownloadManager.Query(); query.SetFilterById(downloadId); ICursor cursor = manager.InvokeQuery(query); if (cursor.MoveToFirst()) { var soFar = cursor.GetDouble(cursor.GetColumnIndex(DownloadManager.ColumnBytesDownloadedSoFar)); var total = cursor.GetDouble(cursor.GetColumnIndex(DownloadManager.ColumnTotalSizeBytes)); RunOnUiThread(() => { progressBar.SetProgress(System.Convert.ToInt32(soFar / total * 100), true); textView1.Text = string.Format("{0} %", Convert.ToInt32(soFar / total * 100)); }); System.Console.WriteLine(soFar.ToString()); if (soFar.Equals(total)) { break; } } Thread.Sleep(500); } }); }
public override void OnReceive(Context context, Intent intent) { try { if (intent.Action == DownloadManager.ActionDownloadComplete) { if (ActivityContext == null) { return; } DownloadManager downloadManagerExcuter = (DownloadManager)ActivityContext.GetSystemService(Context.DownloadService); long downloadId = intent.GetLongExtra(DownloadManager.ExtraDownloadId, -1); DownloadManager.Query query = new DownloadManager.Query(); query.SetFilterById(downloadId); ICursor c = downloadManagerExcuter.InvokeQuery(query); var sqlEntity = new SqLiteDatabase(); if (c.MoveToFirst()) { int columnIndex = c.GetColumnIndex(DownloadManager.ColumnStatus); if (c.GetInt(columnIndex) == (int)DownloadStatus.Successful) { string downloadedPath = c.GetString(c.GetColumnIndex(DownloadManager.ColumnLocalUri)); ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo(); ActivityManager.GetMyMemoryState(appProcessInfo); if (appProcessInfo.Importance == Importance.Foreground || appProcessInfo.Importance == Importance.Background) { sqlEntity.Update_WatchOfflineVideos(Video.VideoId, downloadedPath); if (TypeActivity == "Main") { TabbedMainActivity.GetInstance()?.VideoActionsController.DownloadIcon.SetImageResource(Resource.Drawable.ic_checked_red); TabbedMainActivity.GetInstance().VideoActionsController.DownloadIcon.Tag = "Downloaded"; TabbedMainActivity.GetInstance()?.LibrarySynchronizer.AddToWatchOffline(Video); } else if (TypeActivity == "GlobalPlayer") { GlobalPlayerActivity.GetInstance()?.VideoActionsController.DownloadIcon.SetImageResource(Resource.Drawable.ic_checked_red); GlobalPlayerActivity.GetInstance().VideoActionsController.DownloadIcon.Tag = "Downloaded"; GlobalPlayerActivity.GetInstance()?.LibrarySynchronizer.AddToWatchOffline(Video); } else { if (ActivityContext is FullScreenVideoActivity fullScreen) { fullScreen.VideoActionsController.DownloadIcon.SetImageResource(Resource.Drawable.ic_checked_red); fullScreen.VideoActionsController.DownloadIcon.Tag = "Downloaded"; //fullScreen tabbedMain.LibrarySynchronizer.OfflineVideoList.Add(Video); } } } else { sqlEntity.Connect(); sqlEntity.Update_WatchOfflineVideos(Video.VideoId, downloadedPath); sqlEntity.Close(); } } } } } catch (Exception exception) { Console.WriteLine(exception); } }
/// <summary> /// This will not be used in iOS /// </summary> /// <param name="fileDir">File directory</param> /// <param name="fileName">File name</param> /// <param name="fileDescription">Description to be used to add to the download manager</param> /// <returns>status - true: worked; false: failure</returns> public bool SetDownload(string fileDir, string fileName, string fileDescription) { bool permissionGranted = false; const string mimeUriFile = "file://"; const string excelMimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Version version = DeviceInfo.Version; // This should not be used at or after version 8 (API 26) if (version.Major >= 8) { return(true); } try { var context = Android.App.Application.Context; permissionGranted = true; string fileSpec = Path.Combine(fileDir, fileName); FileInfo fileInfo = new FileInfo(fileSpec); if (fileInfo.Exists) { // Notify the user about the completed "download" DownloadManager downloadManager = DownloadManager.FromContext(context); // https://www.sandersdenardi.com/using-the-android-downloadmanager/ // https://docs.microsoft.com/en-us/dotnet/api/android.app.downloadmanager.invokequery?view=xamarin-android-sdk-9#Android_App_DownloadManager_InvokeQuery_Android_App_DownloadManager_Query_ // have we already added the file to the download manager? DownloadManager.Query query = new DownloadManager.Query(); query.SetFilterByStatus(DownloadStatus.Pending | // <- note bitwise OR DownloadStatus.Running | DownloadStatus.Successful); ICursor cursor = downloadManager.InvokeQuery(query); int colDescrption = cursor.GetColumnIndex(DownloadManager.ColumnDescription); int colDirectory = cursor.GetColumnIndex(DownloadManager.ColumnLocalUri); int colMimeType = cursor.GetColumnIndex(DownloadManager.ColumnMediaType); int colFileName = cursor.GetColumnIndex(DownloadManager.ColumnTitle); bool exactMatchFile = false; bool exactMatchDir = false; bool exactMatchDesc = false; for (cursor.MoveToFirst(); !cursor.IsAfterLast; cursor.MoveToNext()) { string dmFileName = cursor.GetString(colFileName); if (string.IsNullOrEmpty(dmFileName)) { dmFileName = string.Empty; } if (dmFileName.Equals(fileName)) { exactMatchFile = true; } string dmDesc = cursor.GetString(colDescrption); if (string.IsNullOrEmpty(dmDesc)) { dmDesc = string.Empty; } if (dmDesc.Equals(fileDescription)) { exactMatchDesc = true; } string dmMimeType = cursor.GetString(colMimeType); if (string.IsNullOrEmpty(dmMimeType)) { dmMimeType = string.Empty; } string dmDirectory = cursor.GetString(colDirectory); if (string.IsNullOrEmpty(dmDirectory)) { dmDirectory = string.Empty; } else { int i = dmDirectory.IndexOf(mimeUriFile, StringComparison.Ordinal); if (i >= 0) { dmDirectory = dmDirectory.Substring(mimeUriFile.Length); } } if (dmDirectory.Equals(fileDir)) { exactMatchDir = true; } if (exactMatchFile && exactMatchDir && exactMatchDesc) { break; } } cursor.Close(); query = null; if (!(exactMatchFile && exactMatchDir && exactMatchDesc)) { downloadManager.AddCompletedDownload(fileInfo.Name, fileDescription, true, excelMimeType, fileInfo.DirectoryName, fileInfo.Length, true); } } return(true); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("SetDownload() filespec: " + fileDir + " desc: " + fileDescription + " permission granted " + permissionGranted + " - exception: " + ex.Message); System.Diagnostics.Debug.Flush(); } return(false); }
/// <summary> /// 开始下载 /// </summary> public void Start(string apkUrl, string apkName) { var receiver = new DownLoadCompleteReceiver(); // 注册广播接收器,当下载完成时自动安装 _context.RegisterReceiver(receiver, new IntentFilter(DownloadManager.ActionDownloadComplete)); if (DownloadMode != DownloadMode.Always) { var filePath = AEnvironment.GetExternalStoragePublicDirectory(DownloadDirectory).Path; file = new JFile(filePath, apkName); if (file.Exists()) { Console.WriteLine(file.Path); if (DownloadMode == DownloadMode.Overwrite) { file.Delete(); //更新下载中的显示 //ContentValues values = new ContentValues (); //values.Put ("deleted", 1); //COLUMN_DELETED = "deleted"; //CONTENT_URI = Uri.parse("content://downloads/my_downloads"); //ALL_DOWNLOADS_CONTENT_URI = Uri.parse("content://downloads/all_downloads") //_context.ContentResolver.Update (ContentUris.WithAppendedId (AUri.Parse ("content://downloads/my_downloads"), _downloadID), values, null, null); _context.ContentResolver.Delete(AUri.Parse("content://downloads/my_downloads"), "_data=?", new string[] { file.Path }); } else { //发送广播 var intent = new Intent(); intent.SetAction(DownloadManager.ActionDownloadComplete); _context.SendBroadcast(intent); return; } } } //判断是否有正在下载的相同任务 DownloadManager.Query downloadQuery = new DownloadManager.Query(); //根据下载状态查询下载任务 downloadQuery.SetFilterByStatus(DownloadStatus.Running); //根据任务编号查询下载任务信息 //downloadQuery.setFilterById(id); var cursor = downloadManager.InvokeQuery(downloadQuery); if (cursor != null) { if (cursor.MoveToNext()) { if (apkUrl.Equals(cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnUri)))) { Toast.MakeText(_context, "已存在的下载任务", ToastLength.Short).Show(); cursor.Close(); return; } } cursor.Close(); } downLoadRequest = new DownloadManager.Request(AUri.Parse(apkUrl)); downLoadRequest.SetTitle(Title); downLoadRequest.SetDescription(Description); downLoadRequest.AllowScanningByMediaScanner(); downLoadRequest.SetVisibleInDownloadsUi(true); //设置在什么网络情况下进行下载 downLoadRequest.SetAllowedNetworkTypes(AllowedNetworkType); //设置通知栏标题 downLoadRequest.SetNotificationVisibility(DownloadVisibility.Visible | DownloadVisibility.VisibleNotifyCompleted); //设置下载文件的mineType downLoadRequest.SetMimeType("application/com.trinea.download.file"); //downLoadRequest.SetDestinationInExternalFilesDir //设置保存位置 downLoadRequest.SetDestinationInExternalPublicDir(DownloadDirectory, apkName); //保存任务ID _downloadID = downloadManager.Enqueue(downLoadRequest); }
private void _download(string url, Action <int> onPercentUpdate, object CancellationToken) { // set up onPercentUpdate - Action should take an integer parameter and display it somehow onPercentUpdate = onPercentUpdate ?? ((percentageAsInteger) => { }); // handle object CancellationToken, since this can be null var cancelToken = CancellationToken != null ? (CancellationToken)CancellationToken : new CancellationToken(); // check to see if cancelled first if (cancelToken.IsCancellationRequested) { cancelToken.ThrowIfCancellationRequested(); } // create an Android.Net.Uri var uri = Android.Net.Uri.Parse(url); // get the downloadManager instance from Android var downloadManager = (DownloadManager)Android.App.Application.Context.GetSystemService(Context.DownloadService); // create a download request and queue it to the downloadManager var request = new DownloadManager.Request(uri); var downloadId = downloadManager.Enqueue(request); // .Enqueue(request) returns the DownloadManager download Id // set a query filter to point to what we are downloading var query = new DownloadManager.Query(); query.SetFilterById(downloadId); var isDownloading = true; // get status of the download here while (isDownloading) { try { // Data from the downloadManager are not provided as typical C# properties. // Android stores downloadManager info in a SQL table. To access it, we must query the table and grab the property info from each column we need var result = downloadManager.InvokeQuery(query); result.MoveToFirst(); var columnNames = result.GetColumnNames(); // Status column holds an integer value that maps to Android.App.DownloadStatus. Ref: https://developer.xamarin.com/api/type/Android.App.DownloadStatus/ // .Pending = 1 // .Running = 2 // .Paused = 4 // .Successful = 8 // .Failed = 16 var statusIndex = result.GetColumnIndex(DownloadManager.ColumnStatus); var status = result.GetInt(statusIndex); if ((status == (int)Android.App.DownloadStatus.Successful) || (status == (int)Android.App.DownloadStatus.Failed)) { isDownloading = false; } var totalSizeIndex = result.GetColumnIndex(DownloadManager.ColumnTotalSizeBytes); TotalSizeBytes = result.GetLong(totalSizeIndex); var totalDownloadedIndex = result.GetColumnIndex(DownloadManager.ColumnBytesDownloadedSoFar); TotalBytesDownloaded = result.GetLong(totalDownloadedIndex); onPercentUpdate(PercentageDownloaded); System.Diagnostics.Debug.WriteLine(String.Format("Status: {0} | {1}% {2}/{3}", status, PercentageDownloaded, TotalBytesDownloaded, TotalSizeBytes)); // Check for cancellation in loop if (cancelToken.IsCancellationRequested) { cancelToken.ThrowIfCancellationRequested(); } // Sleeping is necessary because our query requests for data seem to operate faster than the DownloadManager // can respond. For example, it can take a few seconds for the DB to be ready before we query it or after // a download completes (see the catch below), thus causing SQL exceptions and other weird behavior. // The sleep offers us a little more time to ensure everything is ready before we query again. Thread.Sleep(1000); } catch (Android.Database.CursorIndexOutOfBoundsException ex) { // this happens when cancelled from the DownloadManager UI if (this.PercentageDownloaded != 100) // percentage check..just in case { throw new DownloadCancelledException("Cancelled", ex, cancelToken); } else { throw ex; } } catch (OperationCanceledException ex) { // this happens when cancellation is processed from within the app somewhere throw new DownloadCancelledException("Cancelled", ex, cancelToken); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(String.Format("Error hit: {0}", ex.Message)); _exceptionList.Add(ex); if (_exceptionList.Count > MaxExceptionCount) { System.Diagnostics.Debug.WriteLine(String.Format("The max number of exceptions allowed has been reached. Allowed: {0}", _maxExceptionCount)); onDownloadFailed(this, null); return; } Thread.Sleep(5000); } } System.Diagnostics.Debug.WriteLine(String.Format("Exited gracefully. Errors: {0}", _exceptionList.Count)); onDownloadCompleted(this, null); }