Skip to content

Instantly share code, notes, and snippets.

@yavor87
Last active March 7, 2020 14:53
Show Gist options
  • Save yavor87/0c2cff20e153fb457186707e565fca0f to your computer and use it in GitHub Desktop.
Save yavor87/0c2cff20e153fb457186707e565fca0f to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Native = Android.App.DownloadManager;
namespace Shiny.Net.Http
{
//https://developer.android.com/reference/android/app/DownloadManager
[BroadcastReceiver(
Name = "com.shiny.net.http.HttpTransferBroadcastReceiver",
Enabled = true,
Exported = true
)]
[IntentFilter(new[] {
Native.ActionDownloadComplete
})]
public class HttpTransferBroadcastReceiver : BroadcastReceiver
{
public static Subject<HttpTransfer> HttpEvents { get; } = new Subject<HttpTransfer>();
public override void OnReceive(Context context, Intent intent)
{
global::Android.Util.Log.Verbose("HttpTransferBroadcastReceiver", "## OnReceive Start");
if (intent.Action != Native.ActionDownloadComplete)
return;
var tdelegate = ShinyHost.Resolve<IHttpTransferDelegate>();
if (tdelegate == null)
return;
this.Execute(async () =>
{
HttpTransfer? transfer = null;
var id = intent.GetLongExtra(Native.ExtraDownloadId, -1);
var native = context.GetService<Native>(Context.DownloadService);
var query = new QueryFilter().Add(id.ToString()).ToNative();
using (var cursor = native.InvokeQuery(query))
{
if (cursor.MoveToNext())
{
global::Android.Util.Log.Verbose("HttpTransferBroadcastReceiver", "## MoveToNext()");
transfer = cursor.ToLib();
if (transfer.Value.Exception != null)
{
global::Android.Util.Log.Verbose("HttpTransferBroadcastReceiver", "## tdelegate.OnError");
await tdelegate.OnError(transfer.Value, transfer.Value.Exception);
}
else
{
var localUri = cursor.GetString(Native.ColumnLocalUri).Replace("file://", String.Empty);
var file = new FileInfo(localUri);
await Task.Run(() =>
{
var to = transfer.Value.LocalFilePath;
if (File.Exists(to))
File.Delete(to);
//File.Copy(localPath, to, true);
File.Move(file.FullName, to);
});
global::Android.Util.Log.Verbose("HttpTransferBroadcastReceiver", "## tdelegate.OnCompleted");
await tdelegate.OnCompleted(transfer.Value);
global::Android.Util.Log.Verbose("HttpTransferBroadcastReceiver", "## tdelegate.OnCompleted end");
}
HttpEvents.OnNext(transfer.Value);
}
}
native.Remove(id);
});
global::Android.Util.Log.Verbose("HttpTransferBroadcastReceiver", "## OnReceive End");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment