下载文件后,Xamarin在通知栏中显示通知

时间:2019-10-16 08:41:09

标签: xamarin xamarin.forms xamarin.android

我有以下代码可以下载运行正确的文件:

var base64EncodedBytes = System.Convert.FromBase64String(item.FileDataAsBase64String);
                var downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
                var filePath = Path.Combine(downloadDirectory, "test.pdf");

                var streamWriter = File.Create(filePath);
                streamWriter.Close();
                File.WriteAllBytes(filePath, base64EncodedBytes);

我能够在“下载”文件夹中找到我下载的文件,但是我还想在通知栏中显示一条通知,指出该文件已下载,并且单击通知后用户便可以打开下载的文件。

有可能吗?

1 个答案:

答案 0 :(得分:1)

下载文件后,您可以使用Plugin.LocalNotification显示通知。

try
{
    var base64EncodedBytes = System.Convert.FromBase64String(item.FileDataAsBase64String);
    var downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
    var filePath = Path.Combine(downloadDirectory, "test.pdf");

    var streamWriter = File.Create(filePath);
    streamWriter.Close();
    File.WriteAllBytes(filePath, base64EncodedBytes);

    DisplayNotification("test.pdf downloaded successfully", filePath);
}
catch(System.Exception e)  
{  
    System.Console.WriteLine(e.ToString());  
    DisplayNotification("Download Failed",string.Empty);
} 


public void DisplayNotification(string message, string filePath)
{
    var notification = new NotificationRequest
    {
        NotificationId = 100,
        Title = "Your App name",
        Description = message,
        ReturningData = filePath, // Returning data when tapped on notification.
        NotifyTime = DateTime.Now.AddSeconds(30) // Used for Scheduling local notification, if not specified notification will show immediately.
    };
    NotificationCenter.Current.Show(notification);
}

注意:请确保在项目iOS和Android中都初始化插件设置。