Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/Plugin.LocalNotifications.Abstractions/ILocalNotifications.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System;

namespace Plugin.LocalNotifications.Abstractions
{
/// <summary>
/// Local Notification Interface
/// </summary>
public interface ILocalNotifications
{
/// <summary>
/// Show a local notification
/// </summary>
/// <param name="title">Title of the notification</param>
/// <param name="body">Body or description of the notification</param>
/// <param name="id">Id of the notification</param>
void Show(string title, string body, int id = 0);

/// <summary>
/// Show a local notification at a specified time
/// </summary>
/// <param name="title">Title of the notification</param>
/// <param name="body">Body or description of the notification</param>
/// <param name="id">Id of the notification</param>
/// <param name="notifyTime">Time to show notification</param>
void Show(string title, string body, int id, DateTime notifyTime);

/// <summary>
/// Cancel a local notification
/// </summary>
/// <param name="id">Id of the notification to cancel</param>
void Cancel(int id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
<!-- A reference to the entire .NET Framework is automatically included -->
</ItemGroup>
<ItemGroup>
<Compile Include="INotifierService.cs" />
<Compile Include="ILocalNotifications.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using System;
using System.IO;
using System.Xml.Serialization;
using Android.App;
using Android.Content;
using Android.Support.V4.App;
using Plugin.LocalNotifications.Abstractions;
using System;
using System.IO;
using System.Xml.Serialization;

namespace Plugin.LocalNotifications
{
Expand All @@ -18,6 +18,19 @@ public class LocalNotificationsImplementation : ILocalNotifications
/// </summary>
public static int NotificationIconId { get; set; }

/// <summary>
/// Gets or sets the optional local notification intent action.
/// </summary>
/// <value>The local notification intent action.</value>
public static string LocalNotificationIntentAction { get; set; }

internal const string LocalNotificationKey = "LocalNotification";

/// <summary>
/// The key of the bundle element that contains notification's id.
/// </summary>
public const string LocalNotificationIntentKey = "NotificationId";

/// <summary>
/// Show a local notification
/// </summary>
Expand All @@ -40,24 +53,26 @@ public void Show(string title, string body, int id = 0)
builder.SetSmallIcon(Resource.Drawable.plugin_lc_smallicon);
}

var resultIntent = GetLauncherActivity();
resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);
stackBuilder.AddNextIntent(resultIntent);
var resultPendingIntent =
stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);
var resultIntent = string.IsNullOrEmpty(LocalNotificationIntentAction) ?
GetLauncherActivity()
:
new Intent(LocalNotificationIntentAction).AddFlags(ActivityFlags.NewTask);

resultIntent.PutExtra(LocalNotificationIntentKey, id);

var resultPendingIntent = PendingIntent.GetActivity(Application.Context, 0, resultIntent, PendingIntentFlags.UpdateCurrent);
builder.SetContentIntent(resultPendingIntent);

var notificationManager = NotificationManagerCompat.From(Application.Context);

notificationManager.Notify(id, builder.Build());
}


public static Intent GetLauncherActivity()
{
var packageName = Application.Context.PackageName;
return Application.Context.PackageManager.GetLaunchIntentForPackage(packageName);
return Application.Context.PackageManager.GetLaunchIntentForPackage(Application.Context.PackageName);
}

/// <summary>
/// Show a local notification at a specified time
/// </summary>
Expand All @@ -74,6 +89,7 @@ public void Show(string title, string body, int id, DateTime notifyTime)
localNotification.Body = body;
localNotification.Id = id;
localNotification.NotifyTime = notifyTime;

if (NotificationIconId != 0)
{
localNotification.IconId = NotificationIconId;
Expand All @@ -84,7 +100,7 @@ public void Show(string title, string body, int id, DateTime notifyTime)
}

var serializedNotification = SerializeNotification(localNotification);
intent.PutExtra(ScheduledAlarmHandler.LocalNotificationKey, serializedNotification);
intent.PutExtra(LocalNotificationKey, serializedNotification);

var pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, intent, PendingIntentFlags.CancelCurrent);
var triggerTime = NotifyTimeInMilliseconds(localNotification.NotifyTime);
Expand All @@ -111,15 +127,12 @@ public void Cancel(int id)

private Intent CreateIntent(int id)
{
return new Intent(Application.Context, typeof(ScheduledAlarmHandler))
.SetAction("LocalNotifierIntent" + id);
return new Intent(Application.Context, typeof(ScheduledAlarmHandler)).SetAction("LocalNotifierIntent" + id);
}


private AlarmManager GetAlarmManager()
{
var alarmManager = Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;
return alarmManager;
return Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;
}

private string SerializeNotification(LocalNotification notification)
Expand All @@ -128,6 +141,7 @@ private string SerializeNotification(LocalNotification notification)
using (var stringWriter = new StringWriter())
{
xmlSerializer.Serialize(stringWriter, notification);

return stringWriter.ToString();
}
}
Expand All @@ -137,8 +151,7 @@ private long NotifyTimeInMilliseconds(DateTime notifyTime)
var utcTime = TimeZoneInfo.ConvertTimeToUtc(notifyTime);
var epochDifference = (new DateTime(1970, 1, 1) - DateTime.MinValue).TotalSeconds;

var utcAlarmTimeInMillis = utcTime.AddSeconds(-epochDifference).Ticks / 10000;
return utcAlarmTimeInMillis;
return utcTime.AddSeconds(-epochDifference).Ticks / 10000;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<AndroidUseLatestPlatformSdk>False</AndroidUseLatestPlatformSdk>
<TargetFrameworkVersion>v4.4</TargetFrameworkVersion>
<AndroidTlsProvider></AndroidTlsProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
Expand All @@ -42,9 +43,8 @@
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Xml" />
<Reference Include="Xamarin.Android.Support.v4, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Xamarin.Android.Support.v4.23.0.1.3\lib\MonoAndroid403\Xamarin.Android.Support.v4.dll</HintPath>
<Private>True</Private>
<Reference Include="Xamarin.Android.Support.v4">
<HintPath>..\..\..\packages\Xamarin.Android.Support.v4.23.3.0\lib\MonoAndroid403\Xamarin.Android.Support.v4.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
Expand All @@ -58,12 +58,12 @@
<Compile Include="ScheduledAlarmHandler.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="Resources\AboutResources.txt" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Plugin.LocalNotifications.Abstractions\Plugin.LocalNotifications.Abstractions.csproj">
<Project>{2906ba0a-cd3e-4ab3-9e8c-7b4da836fa1f}</Project>
<Project>{57564CE6-C079-47C5-9272-4395A0224C3D}</Project>
<Name>Plugin.LocalNotifications.Abstractions</Name>
</ProjectReference>
</ItemGroup>
Expand Down
26 changes: 12 additions & 14 deletions src/Plugin.LocalNotifications.Android/ScheduledAlarmHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,14 @@ namespace Plugin.LocalNotifications
[BroadcastReceiver(Enabled = true, Label = "Local Notifications Plugin Broadcast Receiver")]
public class ScheduledAlarmHandler : BroadcastReceiver
{
/// <summary>
///
/// </summary>
public const string LocalNotificationKey = "LocalNotification";

/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="intent"></param>
public override void OnReceive(Context context, Intent intent)
{
var extra = intent.GetStringExtra(LocalNotificationKey);
var extra = intent.GetStringExtra(LocalNotificationsImplementation.LocalNotificationKey);
var notification = DeserializeNotification(extra);

var builder = new NotificationCompat.Builder(Application.Context)
Expand All @@ -33,25 +28,28 @@ public override void OnReceive(Context context, Intent intent)
.SetSmallIcon(notification.IconId)
.SetAutoCancel(true);

var resultIntent = LocalNotificationsImplementation.GetLauncherActivity();
resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);
stackBuilder.AddNextIntent(resultIntent);
var resultPendingIntent =
stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);
var resultIntent = string.IsNullOrEmpty(LocalNotificationsImplementation.LocalNotificationIntentAction) ?
LocalNotificationsImplementation.GetLauncherActivity()
:
new Intent(LocalNotificationsImplementation.LocalNotificationIntentAction).AddFlags(ActivityFlags.NewTask);

resultIntent.PutExtra(LocalNotificationsImplementation.LocalNotificationIntentKey, notification.Id);

var resultPendingIntent = PendingIntent.GetActivity(Application.Context, 0, resultIntent, 0);
builder.SetContentIntent(resultPendingIntent);

var notificationManager = NotificationManagerCompat.From(Application.Context);

notificationManager.Notify(notification.Id, builder.Build());
}

private LocalNotification DeserializeNotification(string notificationString)
{
var xmlSerializer = new XmlSerializer(typeof(LocalNotification));

using (var stringReader = new StringReader(notificationString))
{
var notification = (LocalNotification)xmlSerializer.Deserialize(stringReader);
return notification;
return (LocalNotification)xmlSerializer.Deserialize(stringReader);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Plugin.LocalNotifications.Android/packages.config
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Xamarin.Android.Support.v4" version="23.0.1.3" targetFramework="monoandroid44" />
<package id="Xamarin.Android.Support.v4" version="23.3.0" targetFramework="monoandroid44" />
</packages>
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;
using Plugin.LocalNotifications.Abstractions;
using System.Linq;
using Foundation;
using Plugin.LocalNotifications.Abstractions;
using UIKit;
using UserNotifications;

Expand All @@ -25,6 +25,7 @@ public void Show(string title, string body, int id = 0)
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(.1, false);

ShowUserNotification(title, body, id, trigger);
}
else
Expand All @@ -45,6 +46,7 @@ public void Show(string title, string body, int id, DateTime notifyTime)
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
var trigger = UNCalendarNotificationTrigger.CreateTrigger(GetNSDateComponentsFromDateTime(notifyTime), false);

ShowUserNotification(title, body, id, trigger);
}
else
Expand Down Expand Up @@ -75,8 +77,7 @@ public void Cancel(int id)
else
{
var notifications = UIApplication.SharedApplication.ScheduledLocalNotifications;
var notification = notifications.Where(n => n.UserInfo.ContainsKey(NSObject.FromObject(NotificationKey)))
.FirstOrDefault(n => n.UserInfo[NotificationKey].Equals(NSObject.FromObject(id)));
var notification = notifications.Where(n => n.UserInfo.ContainsKey(NSObject.FromObject(NotificationKey))).FirstOrDefault(n => n.UserInfo[NotificationKey].Equals(NSObject.FromObject(id)));

if (notification != null)
{
Expand All @@ -96,9 +97,10 @@ void ShowUserNotification(string title, string body, int id, UNNotificationTrigg
var content = new UNMutableNotificationContent()
{
Title = title,
Body = body
Body = body,
UserInfo = NSDictionary.FromObjectAndKey(NSObject.FromObject(id), NSObject.FromObject(NotificationKey))
};

var request = UNNotificationRequest.FromIdentifier(id.ToString(), content, trigger);

UNUserNotificationCenter.Current.AddNotificationRequest(request, (error) => { });
Expand All @@ -117,4 +119,4 @@ NSDateComponents GetNSDateComponentsFromDateTime(DateTime dateTime)
};
}
}
}
}