I want to create ingame pause, so I register local notification to notify user when it's ended.
But there are different purposes for local notification that I use.
So I used userInfo to mark a notification that responsible for pause.
private void ScheduleNotification(DateTime date, string message)
{
#if UNITY_IOS
LocalNotification not = new LocalNotification();
not.applicationIconBadgeNumber = NotificationServices.localNotificationCount + 1;
not.alertBody = message;
not.fireDate = date;
not.userInfo["pause"] = 0;
NotificationServices.ScheduleLocalNotification(not);
#endif
}
But I don't know how to get LocalNotification that was activated, how to do it?
Related
I have azure push notification in Xamarin forms. when push notification received I need to open a page in my application. Its working fine in android. In iOS its not working when app is open. When app is in the background its working find in iOS.
This is my App Delegate code
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo,
Action<UIBackgroundFetchResult> completionHandler)
{
try
{
UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
NSError error;
NSData notification = NSJsonSerialization.Serialize(userInfo["action"], NSJsonWritingOptions.PrettyPrinted, out error);
string notificationString = NSString.FromData(notification, NSStringEncoding.UTF8).ToString();
var NotificationObj = JsonConvert.DeserializeObject<NotificationData>(notificationString);
NotificationService.pushPageName = NotificationObj.Notification[0].PageName.ToString();
NotificationService.pushAppName = NotificationObj.AppName.ToString();
NotificationService.OpenPages = NotificationObj.Notification[0].OpenPage;
NotificationService.Notification = notificationString;
if (UIApplication.SharedApplication.ApplicationState.Equals(UIApplicationState.Active))
{
//App is in foreground. Act on it.
var application1 = new App(NotificationService.pushPageName, NotificationService.pushAppName, NotificationService.Notification);
LoadApplication(application1);
}
else
{
// var application1 = new App(NotificationService.pushPageName, NotificationService.pushAppName, NotificationService.Notification);
// LoadApplication(application1);
}
}
catch (Exception ex)
{
//LogInfo.ReportErrorInfo(ex.Message, ex.StackTrace, "AppDelegate-DidReceiveRemoteNotification");
}
}
after click push notification I need to open splash screen again.
This is App.cs Code
public App(string openPageName, string openAppName,string notification)
{
ServiceContainer.Resolve<IPushNotificationActionService>()
.ActionTriggered += NotificationActionTriggered;
InitMainPage(openPageName, openAppName, notification);
}
private void InitMainPage(string pageName,string appName,string notification)
{
ServiceContainer.Resolve<IPushNotificationActionService>()
.ActionTriggered += NotificationActionTriggered;
PushNotificationActionService.PushNotificationPageName = pageName ;
PushNotificationActionService.PushNotificationAppName = appName;
PushNotificationActionService.PushNotificationMessage = notification;
MainPage = new NavigationPage(new Splash(pageName));
}
All methods are calling and push notification data also loading correctly in iOS. But not navigating to Spalsh Screen. Anyone have an idea to resolve this please help.
If the app is running, we don't need to reload app with LoadApplication , we can directly send message to set MainPage in App.cs .
iOS
if (UIApplication.SharedApplication.ApplicationState.Equals(UIApplicationState.Active))
{
MessagingCenter.Send<object>(this,"Hi");
}
Forms
public App()
{
InitializeComponent();
MainPage = new MainPage();
MessagingCenter.Subscribe<object>(this, "Hi", (obj) => {
MainPage = new NavigationPage(new Splash(pageName));
});
}
I'm using messaging center to fire notification. First one works fine. But the second one is not firing.
MessagingCenter.Subscribe<string>(this, "iOSNotification", (value) =>
{
NotificationDelegate.RegisterNotification("Trip started");
});
MessagingCenter.Subscribe<string>(this, "IosNotMoved", (value) =>
{
NotificationDelegate.RegisterNotification("Would you like to stop trip?");
});
public static void RegisterNotification(string notify)
{
UILocalNotification notification = new UILocalNotification();
notification.FireDate = NSDate.FromTimeIntervalSinceNow(1);
notification.AlertAction = "View Alert";
notification.AlertBody = notify;
UIApplication.SharedApplication.ScheduleLocalNotification(notification);
}
Notification permission should be requested as soon as the app launches by adding the following code to the FinishedLaunching method of the AppDelegate and setting the desired notification type (UNAuthorizationOptions):
...
using UserNotifications;
...
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
....
//after iOS 10
if(UIDevice.CurrentDevice.CheckSystemVersion(10,0))
{
UNUserNotificationCenter center = UNUserNotificationCenter.Current;
center.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.UNAuthorizationOptions.Badge, (bool arg1, NSError arg2) =>
{
});
center.Delegate = new NotificationDelegate();
}
else if(UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert| UIUserNotificationType.Badge| UIUserNotificationType.Sound,new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
return true;
}
New to iOS 10, an app can handle Notifications differently when it is in the foreground and a Notification is triggered. By providing a UNUserNotificationCenterDelegate and implementing the UserNotificationCentermethod, the app can take over responsibility for displaying the Notification. For example:
using System;
using ObjCRuntime;
using UserNotifications;
namespace xxx
{
public class NotificationDelegate:UNUserNotificationCenterDelegate
{
public NotificationDelegate()
{
}
public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
// Do something with the notification
Console.WriteLine("Active Notification: {0}", notification);
// Tell system to display the notification anyway or use
// `None` to say we have handled the display locally.
completionHandler(UNNotificationPresentationOptions.Alert|UNNotificationPresentationOptions.Sound);
}
public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
// Take action based on Action ID
switch (response.ActionIdentifier)
{
case "reply":
// Do something
break;
default:
// Take action based on identifier
if (response.IsDefaultAction)
{
// Handle default action...
}
else if (response.IsDismissAction)
{
// Handle dismiss action
}
break;
}
// Inform caller it has been handled
completionHandler();
}
}
}
To create and register a Custom Action with the system, use the following code:
public void RegisterNotification(long time)
{
UNUserNotificationCenter center = UNUserNotificationCenter.Current;
//creat a UNMutableNotificationContent which contains your notification content
UNMutableNotificationContent notificationContent = new UNMutableNotificationContent();
notificationContent.Title = "xxx";
notificationContent.Body= "xxxx";
notificationContent.Sound = UNNotificationSound.Default;
UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(time, false);
UNNotificationRequest request = UNNotificationRequest.FromIdentifier("FiveSecond", notificationContent, trigger);
center.AddNotificationRequest(request,(NSError obj) =>
{
});
}
When you call this method ,for emample:
RegisterNotification(20);//set the time you want to push notification
The notification will been pushed after 20 seconds,enen if you close your app.
And you can access the link for more information and details: MicroSoft Document
I have the latest Notification ANE for iOS at the moment and I have a couple of questions about set up and display of these notifications
When I set up categories is it necessary to set all the parameters that appear in the example to show actions?(or for example we can set up categories without including .setIcon( "ic_stat_distriqt_default" ) for example) This is the code I am using to set up a category:
service.categories.push(
new CategoryBuilder()
.setIdentifier( Constants.REMINDER_CATEGORY )
.addAction(
new ActionBuilder()
.setTitle( "Snooze" )
.setIdentifier( "ACCEPT_IDENTIFIER" )
.build()
)
.addAction(
new ActionBuilder()
.setTitle( "Accept" )
.setDestructive( true )
.setIdentifier( "DELETE_IDENTIFIER" )
.build()
)
.build()
);
One the other hand I am using for now two types of notification, simple and delayed. Simple notification is being displayed normally in notifications box and the event is being dispatched, however delayed notifications is not being displayed in notifications box but event is being dispatched.(Both cases with App open)
Is this the normal behaviour of delayed notification?
Will App dispatch and receive a delayed notification even if it's closed?
Here it's my code for both cases:
//simple notification
public function notifySimple(vo:LocalNotificationVO):void{
if (Notifications.isSupported)
{
_service.notify(
new NotificationBuilder()
.setId( vo.id )
.setAlert( vo.type )
.setTitle( vo.tittle +": "+vo.body)
.setBody( vo.body )
// .setSound( vo.soundPath )
.enableVibration(vo.enableVibration)
.setPayload( vo.payload )
.build()
);
}
}
//Delayed notification
public function setReminderNotification(vo:LocalNotificationVO):void
{
if (Notifications.isSupported)
{
_service.notify(
new NotificationBuilder()
.setId( vo.id )
.setDelay( vo.delay ) // Show the notification 5 seconds in the future
.setRepeatInterval( NotificationRepeatInterval.REPEAT_NONE ) // Repeat the notification every hour
.setAlert( vo.tittle )
.setTitle( vo.body ) //
.setBody( vo.body ) //Body is not displayed
// .setSound( vo.soundPath ) //SOUNDS DISABLED FOR NOW
// .enableVibration(vo.enableVibration)
// .setPayload( vo.payload )
// .setCategory( Constants.REMINDER_CATEGORY )
.build()
);
}
}
Being LocalNotificationVO (With getters that I didn't include):
public function LocalNotificationVO(id:int,
type:String,
tittle:String,
body:String,
payload:String,
delay:int = 0,
enableVibration:Boolean = true,
soundPath:String = "") {
_id = id;
_type = type;
_tittle = tittle;
_body = body;
_payload = payload;
_delay = delay;
_enableVibration = enableVibration;
_soundPath = soundPath;
}
Thank you very much in advance
i try to play a sound for remote notifications. the app is registered for remoteNotificatiosTypeSound, the sound is enable in notifications phone settings.
the structure of remote notification is like that in console:
{
aps = {
alert = "Notification received";
badge = 1;
payload = {
action = A;
date = "2014-09-16";
idmessage = 243722;
message = "";
time = "11:39:33";
title = "";
};
sound = alarm4.wav;
};
}
It is an error somewhere?
Thank you
sound = alarm4.wav
Does the device have this sound file?
Try
"sound": "default"
Also, this should be a JSON string so you should have : instead of =
I am adding a reminder to a calendar entry. i am using this piece of code,
ContentValues eventValues = new ContentValues();
eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, _calId);
eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Test Event");
eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, "This is an event created for demo app");
eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(DateTime.Today, DateTime.Now));
eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(DateTime.Today.AddDays(1), DateTime.Now));
eventValues.Put(CalendarContract.Events.InterfaceConsts.HasAlarm, true);
eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "Local");
eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "Local");
var eventUri = ContentResolver.Insert(CalendarContract.Events.ContentUri,
eventValues);
long eventID = long.Parse(eventUri.LastPathSegment);
string reminderUriString = "content://com.android.calendar/reminders";
ContentValues reminderValues = new ContentValues();
// reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.CalendarId, _calId);
reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.EventId, eventID);
reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Method, RemindersMethod.Alert.ToString());
reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Minutes, 5);
Android.Net.Uri url = Android.Net.Uri.Parse(reminderUriString);
var reminderUri = ContentResolver.Insert(url, reminderValues);
this doesnt give any exception but does not add the reminder either. what is wrong? How do i add reminder?i do have write permission. I am able to add calendar events but not able to add reminders
RemindersMethod is an enum, so you need to cast it to an int.
So change your code for adding Reminder method to:
remindersValues.Put(
CalendarContract.Reminders.InterfaceConsts.Method,
(int) RemindersMethod.Alert
);