Xamarin display notification in notification bar once the file is downloaded - xamarin

I have this code for downloading a file which runs correct:
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);
I'm able to locate the file I downloaded in the Downloads folder, but also I want to show a notification in the notification bar that the file has been downloaded and with a click in the notifications the user to be able to open the downloaded file.
Is that possible?

You can use Plugin.LocalNotification to show the notification once the file is downloaded.
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);
}
Note: Make sure to initialize the plugin setup in both the project iOS and Android.

Related

receive file in my xamarin app from another's app share function

How to receive file in my xamarin app from another's app share function?
if (Intent.Action == Intent.ActionSend)
{
{
// This is just an example of the data stored in the extras
var uriFromExtras = Intent.GetParcelableExtra(Intent.ExtraStream) asAndroid.Net.Uri;
var subject = Intent.GetStringExtra(Intent.ExtraSubject);
// Get the info from ClipData
var pdf = Intent.ClipData.GetItemAt(0);
// Open a stream from the URI
var pdfStream = ContentResolver.OpenInputStream(pdf.Uri);
// Save it over
var memOfPdf = new System.IO.MemoryStream();
pdfStream.CopyTo(memOfPdf);
var docsPath = System.Environment.GetFolderPat(System.Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(docsPath, "temp.pdf");
System.IO.File.WriteAllBytes(filePath, memOfPdf.ToArray());
mainForms.DisplayThePDF(filePath);
}
}
this is only for PDF and also not working well.

Play custom sound in Xamarion IOS local notification

I am trying to play custom mp3 sound file of (10-25 seconds) with local notification. I have placed the custom sound file in iOS project folder (same level as Resources) with BundleResource as BuildAction. I have also placed the sound file in Resources folder with same build action. It seems both doesn't work.
var content = new UNMutableNotificationContent
{
Title = title,
//Subtitle = "Notification Subtitle",
Body = body,
Badge = 1,
Sound = UNNotificationSound.GetSound("music.mp3"), //play custom sound
UserInfo = NSDictionary.FromObjectAndKey(NSObject.FromObject(id), NSObject.FromObject(notificationKey))
};
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(10, false);
var requestID = "request_" + id;
var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
{
if (err != null)
{
throw new Exception($"Failed to schedule notification: {err}");
}
});
Any suggestion?
The code works fine, my phone sound was mute.

Toast notification not working in Xamarin UWP Windows app

I have UWP Windows application, developed under the Xamarin.forms. I have implemented the Toast notifications but I am facing the issue with this. In some Windows 10 systems, it is working and showing the toast notification properly, but in some of the Windows 10 systems (even having the same Windows 10 OS update) it is not working.
Below first code snippets that I have implemented in the Native UWP.
string msg = "Toast Notification Header";
string subMsg = "Toast Notification Title";
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
var toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode(msg));
toastTextElements[1].AppendChild(toastXml.CreateTextNode(subMsg));
//To play the custom sound
var toastNode = toastXml.SelectSingleNode("/toast");
var audio = toastXml.CreateElement("audio");
audio.SetAttribute("src", "ms-appx:///Assets/incoming_message.wav");
audio.SetAttribute("loop", "false");
toastNode.AppendChild(audio);
var toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
Below second code snippets that I have implemented in the Native UWP.
// "With Microsoft.Toolkit.Uwp.Notifications"
// Construct the toast content
ToastContent toastContent = new ToastContent()
{
Visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText()
{
Text = "Toast Notification Header"
},
new AdaptiveText()
{
Text = "Toast Notification Content"
}
}
}
}
};
bool supportsCustomAudio = true;
// If we're running on Desktop before Version 1511, do NOT include custom audio
// since it was not supported until Version 1511, and would result in a silent toast.
if (AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Desktop")
&& !ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 2))
{
supportsCustomAudio = false;
}
if (supportsCustomAudio)
{
toastContent.Audio = new ToastAudio()
{
Src = new Uri("ms-appx:///Assets/incoming_message.wav")
};
}
// And create the toast notification
ToastNotification notification = new ToastNotification(toastContent.GetXml());
// And then send the toast
ToastNotificationManager.CreateToastNotifier().Show(notification);
Above code snips showing the Toast notification in some Windows 10 system and not working in some other Windows 10 system.
Kindly guide me on this. Thanks in advance.
Regards,
Vivek
Please follow these steps to add toast notification in UWP Project.
Step 1:- Create a new UWP project.
Step 2:- Go to the code-behind and add the namespace.
using Windows.UI.Notifications;
using
NotificationsExtensions.Toasts;
Step 3:- I created a Toast Generic Template like the following code:
public static Windows.Data.Xml.Dom.XmlDocument CreateToast()
{
var xDoc = new XDocument(
new XElement("toast",
new XElement("visual",
new XElement("binding", new XAttribute("template", "ToastGeneric"),
new XElement("text", "C# Corner"),
new XElement("text", "Do you got MVP award?")
)
),// actions
new XElement("actions",
new XElement("action", new XAttribute("activationType", "background"),
new XAttribute("content", "Yes"), new XAttribute("arguments", "yes")),
new XElement("action", new XAttribute("activationType", "background"),
new XAttribute("content", "No"), new XAttribute("arguments", "no"))
)
)
);
var xmlDoc = new Windows.Data.Xml.Dom.XmlDocument();
xmlDoc.LoadXml(xDoc.ToString());
return xmlDoc;
}
Step 4:- Create a toast notification object using XML document.
var xmdock = CreateToast();
var toast = new ToastNotification(xmdock);
Next show the toast using ToastNotificationManager class.
var notifi = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();
notifi.Show(toast);
Step 5:- C# code-behind:
private void showToastBtn_Click(object sender, RoutedEventArgs e)
{
var xmdock = CreateToast();
var toast = new ToastNotification(xmdock);
var notifi = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();
notifi.Show(toast);
}
I hope the above code will be useful for you.
Thank you

create local notification in xamarin ios with http request

i have xamarin forms app that support notification, i have done it in android with broadcast receiver now i have to do notification in ios ! , my service is depending on API REST so i want every 60 second ios app run HTTP request and get data then show it as notification, i searched for many days but i can't reach to my approach ?
if this is impossible can i use nuget or something like that in ios project only "in xamarin forms solution " or not ?
content = new UNMutableNotificationContent();
content.Title = "Notification Title";
content.Subtitle = "Notification Subtitle";
content.Body = "This is the message body of the notification.";
content.Badge = 1;
content.CategoryIdentifier = "message";
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(60, true);
var requestID = "sampleRequest";
var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
{
if (err != null)
{
// Do something with error...
}
});
Here is my code for generating a local notification on iOS
var alertsAllowed = false;
UNUserNotificationCenter.Current.GetNotificationSettings((settings) =>
{
alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
});
if (alertsAllowed)
{
var content = new UNMutableNotificationContent();
content.Title = "Incident Recorder";
content.Subtitle = "Not Synchronised";
content.Body = "There are one or more new incidents that have not been synchronised to the server.";
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);
var requestID = "sampleRequest";
var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
{
if (err != null)
{
Console.WriteLine(err.LocalizedFailureReason);
}
});
}
The first parameter in CreateTrigger is how long before the notification is generated. I notice you have 60 in yours. Also bear in mind a notification will not appear if your app is foregrounded.

Firefox add-on access all the console log information

I am developing an add-on in Firefox. As a part of the add-on, I am opening a tab with a new page, and once the page is completely loaded, I would like access the web console log information (css/javascript errors.....
How do I access all the console log information once the page is loaded ?
First you have to get the innerID of the window that you want to obtain messages from.
With the sdk you can get this with var innerID = require("sdk/window/utils").getInnerId(require("sdk/view/core").viewFor(require("sdk/windows").activeWindow))
or more cleanly:
var utils = require("sdk/window/utils");
var viewFor = require("sdk/view/core").viewFor;
var windows = require("sdk/windows");
var innerID = utils.getInnerId(viewFor(windows.activeWindow));
Then you want to observe console notifications for that window:
var system = require("sdk/system/events");
system.on('console-api-log-event', onMessage);
function onMessage(subject) {
subject = subject.wrappedJSObject;
if (subject.innerID != innerID) {
return null; //ignore this console log, because it is for a window/thing that I don't care about
}
if (subject.level != "log") {
return null; // ignore anything but console.log, like: console.info, console.error, console.debug, etc.
}
var message = subject.arguments[0]; // first string argument to console.log()
// do something with the console.log("") message
}

Resources