how to stack notification using pushwoosh in xamarin android - c#

how to stack notification using pushwoosh when the app receive multiple message, i have search all over the internet but i didn't get answer. in this reference
public void doOnMessageReceive(String message)
{
// code to run when device receives notification
}
i should create a code in doOnMessageReceive when the app receive message so i create this code
const int intnumer = 100;
var resultIntent = new Intent(this, typeof (MainActivity));
var stackBuilder = TaskStackBuilder.Create(this);
stackBuilder.AddParentStack(Class.FromType(typeof (MainActivity)));
stackBuilder.AddNextIntent(resultIntent);
var resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
var builder = new NotificationCompat.Builder(this)
.SetAutoCancel(true)
.SetContentIntent(resultPendingIntent)
.SetContentTitle("Yeah")
.SetSmallIcon(Resource.Drawable.ic_action_home)
.SetContentText(string.Format("The button has been clicked"));
var notificationManager = (NotificationManager) GetSystemService(NotificationService);
notificationManager.Notify(intnumer,builder.Build());
but the behavior is like when i receive the message this pop on notification bar
then click on it this will pop up
anyone can help me?

Related

send push notification from one android app to another when data in sql server database changes

i am trying to understand how an android app on a device could send a notification to another android app on another device when a user adds a record to sql server database or deletes one. i started my research and figured out that i must use FCM. i applied this tutorial https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=windows and it worked but it didn't help me understand how the android app well send the notification. i tried to apply codes from java like this one https://blog.heyday.xyz/send-device-to-device-push-notifications-without-server-side-code-238611c143, i tried to convert it to c# but it didn't work for me. i actually didn't know how to completely write it as c#. i also tried this one: Xamarin android FCM Notification Client to client(phone to phone) but in vain. i searched a lot but i don't know why it feels complicated. if anyone could help me find a tutorial to do so. thanks in advance.
To send notifications from one device to another in Xamarin.android there are several ways:
using firebase cloud messaging when add new row to database
Example:
//process that add new row
//post on FCM
note: receive device must be register device token in firebase cloud messaging
for more details:
https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/firebase-cloud-messaging
using task work in background in reciver device and check the number of row in database
example:
Task.Run(()=>{
//code that check number of row
});
if changed call this method :
public void SendNotification(int periority_notification, return_user_info User_info, Context context)
{
/*here intent to open layout when click on notification*/
Intent inten = new Intent(context, typeof(MainActivity));
const int pendingIntentId = 0;
PendingIntent pendingIntent =
PendingIntent.GetActivity(context, pendingIntentId, inten, PendingIntentFlags.OneShot);
var title = User_info.User_Email;
var message = User_info.User_Name.Trim() + " Reserved Request";
using (var notificationManager = NotificationManager.FromContext(context))
{
Notification notification;
if (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.O)
{
notification = new Notification.Builder(context)
.SetContentIntent(pendingIntent)
.SetContentTitle(title)
.SetContentText(message)
.SetAutoCancel(true)
.SetPriority(1)
.SetSmallIcon(Resource.Drawable.carparts)
.SetDefaults(NotificationDefaults.All)
.Build();
}
else
{
var myUrgentChannel = context.PackageName;
const string channelName = "SushiHangover Urgent";
NotificationChannel channel;
channel = notificationManager.GetNotificationChannel(myUrgentChannel);
if (channel == null)
{
channel = new NotificationChannel(myUrgentChannel, channelName, NotificationImportance.High);
channel.EnableVibration(true);
channel.EnableLights(true);
channel.LockscreenVisibility = NotificationVisibility.Public;
notificationManager.CreateNotificationChannel(channel);
}
channel?.Dispose();
notification = new Notification.Builder(context)
.SetContentIntent(pendingIntent)
.SetChannelId(myUrgentChannel)
.SetContentTitle(title)
.SetContentText(message)
.SetAutoCancel(true)
.SetSmallIcon(Resource.Drawable.carparts)
.Build();
}
notificationManager.Notify(periority_notification, notification);
notification.Dispose();
}
}

Creating a notification at a specific time

I have a calendar app that I'm working on, and I need to alert the user to an Upcoming event.
so I want to know what's the best practice to do this, and how should I do it, since the current solution I have isn't even working very well.
the way I do it now is by using an AlarmManager to trigger the a BroadcasReciever that creates and shows the notification.
do I need to use a service? and if so, how should I do it?
CODE:
private void StartDBUpdateAlarm() // Start the alarm manager for event reminder
{
// Get the eventos orded by date (Later than DateTime.Now),
// so that we can get the earliest events
var eventos = eventDao.Select(FromEventos.OrderByDate, DateTime.Now);
if ((eventos.Count > 0)) // Only create notification if there is an event
{
// Create the Intent to pass some info through it to the notification
Intent alarmIntent = new Intent(this, typeof(ReminderReciever));
// Putting the information that will be passed with constant Id's
alarmIntent.PutExtra(GerirUtils.INTENT_TITLE, GetString(Resource.String.main_notification_title));
alarmIntent.PutExtra(GerirUtils.INTENT_INFO, "Info");
alarmIntent.PutExtra(GerirUtils.INTENT_CONTENT, eventos[0].Descricao);
// Creating/Recreating the Pending Intent that will pass the actual information to the notification
PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, GerirUtils.NOTIFICATION_REMINDER_ID, alarmIntent, 0);
// Getting the date and time of the next event, then calculate the diference between DateTime.Now,
// to know how much time it'll be until next event, so that we know when to trigger the notification
DateTime eventDateTime = CalendarHelper.EventDateTime(eventos[0]);
TimeSpan eventMillis = (eventDateTime - GerirUtils.BaseUTCDate); // BaseDate is just the Utc date = 1970/01/01, because the alarm counts millis since then
// Creating and setting the alarm manager
alarm = (AlarmManager)GetSystemService(Context.AlarmService);
alarm.SetExact(AlarmType.RtcWakeup, (long)eventMillis.TotalMilliseconds, pendingIntent);
}
}
BROADCAST RECIEVER CLASS
[BroadcastReceiver(Enabled = true)]
public class ReminderReciever : BroadcastReceiver
{
private string type, title, info, content;
private IList<string> events;
private int notificationId;
private Context context;
public override void OnReceive(Context context, Intent intent)
{
this.context = context;
notificationId = intent.GetIntExtra(GerirUtils.INTENT_ID, -1);
type = intent.GetStringExtra(GerirUtils.INTENT_TYPE);
events = intent.GetStringArrayListExtra(GerirUtils.INTENT_EVENTS);
title = intent.GetStringExtra(GerirUtils.INTENT_TITLE);
info = intent.GetStringExtra(GerirUtils.INTENT_INFO);
content = intent.GetStringExtra(GerirUtils.INTENT_CONTENT);
if(notificationId > -1)
if(type == GerirUtils.NOTIFICATION_TYPE_EVENT_REMINDER)
ShowNotification();
else if(type == GerirUtils.NOTIFICATION_TYPE_ADDED_EVENTS)
ShowNotificationList();
}
private void ShowNotification()
{
Android.Net.Uri sound = RingtoneManager.GetDefaultUri(RingtoneType.Alarm);
NotificationManager mNotificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
NotificationChannel channel = new NotificationChannel("default", title, NotificationImportance.Default) { Description = content };
mNotificationManager.CreateNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "default")
.SetSmallIcon(Resource.Mipmap.ic_calendario_gerir) // notification icon
.SetContentTitle(title) // title for notification
.SetContentText(content) // message for notification
.SetContentInfo(info) // Info message next to content
.SetSound(sound) // set alarm sound for notification
.SetAutoCancel(true); // clear notification after click
Intent intent = new Intent(context, typeof(MainActivity));
PendingIntent pi = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.UpdateCurrent);
mBuilder.SetContentIntent(pi);
mNotificationManager.Notify(0, mBuilder.Build());
}
}
Well,I managed to find the problem after carefully inspecting the code, it looked like I wasn't sending an notificationId, through the intent. the the intent on the BroadcastReviever was always the default -1, so the if statement was always false and, dumb ol' me, didn't put a message warning when the Id was -1, so I had a harder time to find the error then what I would've if I had the message.
and so, the solution was adding this line of code to the program:
private void StartDBUpdateAlarm() // Start the alarm manager for event reminder
{
...
...
if ((eventos.Count > 0)) // Only create notification if there is an event
{
// Create the Intent to pass some info through it to the notification
Intent alarmIntent = new Intent(this, typeof(ReminderReciever));
// MISSING LINE OF CODE
alarmIntent.PutExtra(GerirUtils.INTENT_ID, GerirUtils.NOTIFICATION_REMINDER_ID);
...
...
...
}
}

How Can I set the intent of a service in android to a shared page in Xamarin cross platform

I am trying to set the return page of an android notification to a content page in Xamarin. That is, an android service sends a local notification and when the user clicks on the notification, he is taken to a shared xamarin.forms page.
In the code below, "MyWishList"
is a shared page in the PCL but the code resides in the Android version of the project. Running this code throws an exception
System.ArgumentException: type
Parameter name: Type is not derived from a java type.
It works fine when I change MyWishList to an android activity, but I need to connect the notification to a shared page.
void sendUserNotification(string title, string username)
{
// Pass the current button press count value to the next activity:
Bundle userDetails = new Bundle();
userDetails.PutString(title, username);
// When the user clicks the notification, SecondActivity will start up.
Intent resultIntent = new Intent(this, typeof(MyWishList)); // change mainActivity to wishlist page pcl
// Pass some values to SecondActivity:
resultIntent.PutExtras(userDetails);
// Construct a back stack for cross-task navigation:
TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
stackBuilder.AddNextIntent(resultIntent);
// Create the PendingIntent with the back stack:
PendingIntent resultPendingIntent =
stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);
// Build the notification:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.SetAutoCancel(true) // Dismiss from the notif. area when clicked
.SetContentIntent(resultPendingIntent) // Start 2nd activity when the intent is clicked.
.SetContentTitle("New Notification: " + counter) // Set its title
.SetSmallIcon(Resource.Drawable.zaposta_icon); // Display this icon
// Finally, publish the notification:
NotificationManager notificationManager =
(NotificationManager)GetSystemService(Context.NotificationService);
int notificationId = 0;
notificationManager.Notify(notificationId, builder.Build());
}
I had the same problem. Probably your "MyWishList" activity is the ViewModel. I set the View and I solved it.
I hope this could help others with the same problem.

Using Raw Push notifications in WNS

I've been trying to implement a BackgroundTask for Raw Push Notifications on my Windows and Windows Phone 8.1 apps but it doesn't seem to be working. I've successfully managed to get toast based push notifications working but as far as I'm aware a Raw notification silently pushes data to the app and it's up to the app to display a toast notification or update the app's tile.
I've looked at the BackgroundTask Sample and followed it exactly yet nothing works (https://code.msdn.microsoft.com/windowsapps/Background-Task-Sample-9209ade9).
Here's the steps I've taken
Created a Windows Runtime Component Project in the same solution as my other projects (Called NotificationServer)
Renamed the class to RawTask.cs and implemented IBackgroundTask and its Run method
Created a method to create a toast notification
private void SendNotification(string text)
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
XmlNodeList elements = toastXml.GetElementsByTagName("text");
foreach (IXmlNode node in elements)
{
node.InnerText = text;
}
ToastNotification notification = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(notification);
}
Added code to the Run method
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
string content = notification.Content;
// ...
SendNotification("test");
// ...
_deferral.Complete();
Updated my App's manifest to Toast Capable = YES and Lock Screen Notifications = Badge
Added a Declaration for a Background Task with Supported Task Type = Push Notification and Entry Point = NotificationServer.RawTask
Added code to register the Background Task
public static BackgroundTaskRegistration RegisterBackgroundTask(string taskEntryPoint,
string taskName,
IBackgroundTrigger trigger,
IBackgroundCondition condition)
{
//
// Check for existing registrations of this background task.
//
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == taskName)
{
//
// The task is already registered.
//
return (BackgroundTaskRegistration)(cur.Value);
}
}
//
// Register the background task.
//
var builder = new BackgroundTaskBuilder();
builder.Name = taskName;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
if (condition != null)
{
builder.AddCondition(condition);
}
BackgroundTaskRegistration task = builder.Register();
return task;
}
And executing it with
var reg = RegisterBackgroundTask("NotificationServer.RawTask", "RawNotifications", new PushNotificationTrigger(), null);
Is there something I'm missing here, my app doesn't seem to be responding to the Push Notification event. I have made sure my app is associated with the app in the store and the pushes are being sent with the correct client secret and app ID.
There are four types of push notifications:
Tile update
Badge update
Toast notification
Raw notification
All Windows Runtime apps can use the first three push notifications when in the foreground. Only lock screen apps can receive raw push notifications from WNS.
so, you must make your app a lock screen app.
You can follow this topic to do that.

How to activate an activity using a local notification created from a remote notification

I have successfully created a local notification that starts an activity, but for some reason when this local notification is created from within the handler of a remote notification the activity is not started when the local notification is tapped by the user. No error or exception seems to be thrown.
Below is the code that creates the local notification. Note I'm using Xamarin.
I wonder if it is perhaps somehow permissions related (remote notification handlers maybe cannot create intents to start activities?).
private void CreateNotification(string title, string desc) {
var uiIntent = new Intent(this, typeof(ConversationActivity));
var stackBuilder = TaskStackBuilder.Create(this);
stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(ConversationActivity)));
stackBuilder.AddNextIntent(uiIntent);
PendingIntent pendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);
var notification = new NotificationCompat.Builder(this)
.SetAutoCancel(true) // Remove the notification once the user touches it
.SetContentIntent(pendingIntent)
.SetContentTitle(title)
.SetSmallIcon(Resource.Drawable.AppIcon)
.SetContentText(desc)
.SetDefaults((int)(NotificationDefaults.Sound | NotificationDefaults.Vibrate))
;
// Set the notification info
// we use the pending intent, passing our ui intent over which will get called
// when the notification is tapped.
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
notificationManager.Notify(1, notification.Build());
}
I'm still not sure what was wrong with my original attempt, but I did find out I could fix it by changing the Intent to use a component name instead of an action or activity type:
private void SendNotification() {
var nMgr = (NotificationManager)this.GetSystemService(NotificationService);
var notification = new Notification(Resource.Drawable.AppIcon, "Incoming Dart");
var intent = new Intent();
intent.SetComponent(new ComponentName(this, "dart.androidapp.ContactsActivity"));
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
notification.SetLatestEventInfo(this, "You've got something to read", "You have received a message", pendingIntent);
nMgr.Notify(0, notification);
}
You should be able to call it with typeof(...) as well. The code you posted first is quite different from the latter. Try if this works for you:
private void SendNotification()
{
var nMgr = (NotificationManager)this.GetSystemService(NotificationService);
var notification = new Notification(Resource.Drawable.AppIcon, "Incoming Dart");
var intent = new Intent(this, typeof(ContactsActivity));
//intent.SetComponent(new ComponentName(this, "dart.androidapp.ContactsActivity"));
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
notification.SetLatestEventInfo(this, "You've got something to read", "You have received a message", pendingIntent);
nMgr.Notify(0, notification);
}
Hello Andrew for me bellow is working fine
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "Hello Chitta!", System.currentTimeMillis());
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL , new String[]{"jdsjdjbdf#gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Hello CR!");
intent.putExtra(Intent.EXTRA_TEXT , "This is the body of email");
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
notification.setLatestEventInfo(getApplicationContext(), "Send an e-mail", "Ha ha", pendingIntent);
notificationManager.notify(742134, notification);
Are talking about something else?

Categories