Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to open an xaml page when user clicks on the Notification. I've searched but cant find a decent sample for this situation.
By the way I'm using FCM with old GCM integration.How can I achieve this in android ?
I want to open an xaml page when user clicks on the notification .
When you receive a Notification from FCM, you could add a PendingIntent in Notification to implement this function, this will allow the user to open the app. Code like this :
void SendNotification(string messageBody)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Notification.Builder(this)
.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
.SetContentTitle("FCM Message")
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
For more information, you could read the document and here is the complete code.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have created a log in page for my flutter app that use firebase authentication. can someone help me to use shared preference in this so that user stays logged in even if he kills the app
well, in your login function, you should persist the data in sharePreference if validation is successfull;
/// your statefull code
void login() {
// get the inputValues;
// if validation success do this
this._persistUserInfo();
}
void _persistUserInfo() async {
final sharePrefsInstance = await SharedPreferences.getInstance();
sharePrefsInstance .setString("email", EMAIL_VALUE);
sharePrefsInstance .setString("password", _PASSWORD_VALUE);
}
/// your other statefull code;
the code above will persist the infromation on the device ;
to retrive the data in, in the initState of your LoginScreen do this
#override
void initState() {
super.initState();
Future.delayed(
Duration(seconds: 3),
() async {
final sharePrefsInstance = await SharedPreferences.getInstance();
final email = sharePrefsInstance.getString("email");
final password = sharePrefsInstance.getString("password");
if( email != null && password != null) {
// navigate to your other screen since the user is authenticated
}
},
);
}
I would like to notify online users that a new chat room has been created. I don't need to notify offline users once they come online.
I looked at AbpNotifications but this seems to persist notifications and notify a user once they come online. I only want to notify currently online users.
I looked at SignalR integration but could not find a way for the server to initiate a message. For instance, I might want the ApplicationService.ChatRoom.Create method to initiate the message.
I did find documentation for how to get SignalR (outside of ABP) to initiate a message: https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr#server
Inject and use IRealTimeNotifier.
private async Task SendRealTimeNotificationsAsync(string message, UserIdentifier[] users)
{
var data = new MessageNotificationData(message);
var notification = new TenantNotification { Data = data };
var userNotifications = users.Select(user => new UserNotification
{
TenantId = user.TenantId,
UserId = user.UserId,
Notification = notification
});
await RealTimeNotifier.SendNotificationsAsync(userNotifications.ToArray());
}
More info:
https://aspnetboilerplate.com/Pages/Documents/Notification-System#real-time-notifications
Currently, I have push notifications being sent and received in my Xamarin app. When I send a push notification the sneak peak dialogue is displayed when the app is in the foreground & also the background. I am trying to only visual display a push notification when the app is in the background. When the user is in the foreground the notification just sneaks into the HUD and is not displayed.
Here is my code:
Xamarin Android
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class FCMMessagingService : FirebaseMessagingService
{
const string TAG = "MyFirebaseMsgService";
public override void OnMessageReceived(RemoteMessage message)
{
try
{
var _message = message.GetNotification().Body;
var _title = message.GetNotification().Title;
MainActivity.SendNotification(_title, _message);
}
catch (Exception e)
{
//Was NotificationType null? this should never be null anyways
}
}
}
API - Android Payload
return new JObject(
new JObject(
new JProperty("notification",
new JObject(
new JProperty("body", message),
new JProperty("title", title),
new JProperty("icon","toasticon"),
new JProperty("user", fromId != null ? fromId.ToString() : "")
)
),
new JProperty("data",
new JObject(
new JProperty("notificationtype", notificationType)
)
)
)
).ToString();
If you have followed the firebase setup for xamarin android
You might have read there that foreground notifications have to be displayed manually,
How to do that?
This is how
In the setup, you will have a class inheriting from FirebaseMessagingService
In that class, there will be a piece of code something like this():
var pendingIntent = PendingIntent.GetActivity(this,
MainActivity.NOTIFICATION_ID,
intent,
PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
.SetContentTitle("FCM Message")
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(MainActivity.NOTIFICATION_ID,
notificationBuilder.Build());
This piece of code sends the notification to the Android tray, When in the foreground and hence if you comment this you will get the desired output.
Good luck!
In case of queries revert.
I used these instructions to add Azure Notification Hub FCM-based Remote Notifications to my Xamarin.Forms Android app.
https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-xamarin-forms-get-started-push
I can receive Remote Notifications when the app is open or running in the background, but when I close the application or stop the application I no longer receive Remote Notifications.
My test device is running API level 22, so I'm using the following method to to build the notification on the device.
Android.Support.V4.App.NotificationCompat.Builder builder = new
Android.Support.V4.App.NotificationCompat.Builder(this)
For API level 26+, I'm using the follow method along with a channel to build the notification on the device.
var builder = new Android.App.Notification.Builder(this)
I'm thinking that I have to use a BroadcastReceiver to achieve this, but I really have no idea after reading so many comments on this subject. My app is compiled using API 27 and targets API 27.
Method 1
I'm trying to create a BroadcastReceiver that will launch MyService using an Explicit Intent when a Notification arrives. Unfortunately, this does not work on my API Level 22 test device.
//[BroadcastReceiver]
//[IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
[BroadcastReceiver(Enabled = true, Exported = true)]
[IntentFilter(new[] { "com.xamarin.example.TEST" })]
public class MyBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
string message = intent.GetStringExtra("message");
string title = intent.GetStringExtra("title");
string id = intent.GetStringExtra("id");
//Explicit Intent to launch MyService
Intent intent2 = new Intent(Application.Context, typeof(MyService));
intent2.PutExtra("message", message);
intent2.PutExtra("title", title);
intent2.PutExtra("id", id);
Application.Context.StartService(intent2);
}
}
// Service is exported and given a name so other applications can use it
[Service(Exported = true, Name = "com.mycompany.myapp.MyService")]
// Intent filter only needed for Implicit Intents
//[IntentFilter(new string[] { "com.xamarin.example.TEST" })]
public class MyService : Service
{
public static string PRIMARY_NOTIF_CHANNEL = "default";
public override IBinder OnBind(Intent intent)
{
return null;
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
var pm = PowerManager.FromContext(this);
var wakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "Notification");
wakeLock.Acquire();
string message = intent.GetStringExtra("message");
string title = intent.GetStringExtra("title");
string id = intent.GetStringExtra("id");
var intent2 = new Intent(this, typeof(MainActivity));
intent2.PutExtra("id", id);
intent2.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
Android.Support.V4.App.NotificationCompat.Builder builder = new Android.Support.V4.App.NotificationCompat.Builder(this)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.SetContentTitle(title)
.SetContentText(message)
.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
.SetVibrate(new long[1])
//1 is Hi
.SetPriority(1)
.SetLargeIcon(BitmapFactory.DecodeResource(Resources, SalesFlash.Droid.Resource.Drawable.Icon_lg))
.SetSmallIcon(MyApp.Droid.Resource.Drawable.icon)
.SetChannelId(PRIMARY_NOTIF_CHANNEL);
notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, builder.Build());
wakeLock.Release();
//return StartCommandResult.Sticky;
return base.OnStartCommand(intent, flags, startId);
}
public override void OnDestroy()
{
base.OnDestroy();
}
}
According to this post, a BroadCastReceiver won't work for FCM Notifications. https://stackoverflow.com/a/44287962/5360237
This post seems to show a BroadcastReceiver accepting a Notification.
https://stackoverflow.com/a/45616014/5360237
Any help is much appreciated. Thanks in advance!
Here is the best post that I've read that explains the problem. It also provides a manual solution for the affected devices. https://medium.freecodecamp.org/why-your-push-notifications-never-see-the-light-of-day-3fa297520793 I was able to get Notifications working (when app is closed, stopped or not running) on my Alcatel One Touch Pop by navigating to Settings - Apps and then swiping over to the Restricted tab. From here, I was able to uncheck my app.
NOTE: Messages are delivered to my Android app using the data payload. Even though I was receiving Notifications in the foreground and background, I went ahead and added the following permission to my AndroidManifest.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
This permission is used for Auto Start. I also used Azure App Center to distribute a signed APK to my test device. Hope this helps someone else.
UPDATE: I removed the RECEIVE_BOOT_COMPLETE permission and did a Debug Build. I closed the app out of Debug (connected to Visual Studio) by swiping it off the screen. I then sent a Notification and it did not display. I then re-opened the app (not being debugged by Visual Studio) and closed it by swiping it off the screen, sent a Notification and it worked. So, it had nothing to with the RECEIVE_BOOT_COMPLETE permission and it doesn't have to be a Release version / signed APK.
I am using FCM to send notifications on Android Device of 8.1 version.
I am trying to achieve the grouping of notifications , and i have achieved it.
Whenever first notification is in status bar and second notification arrives the first notification disappears. From Second notification on wards all the notifications are shown in the group as expected.
How to solve it ?
Posting Code Snipper below.
if ("FirstTime".equals(new SharedPrefsOperations(this).getPreferencesData("ActiveNotifs"))) {
// I AM EXECUTING THIS ONLY AT FIRST TIME , WHEN THE FIRST NOTIFICATION ARRIVES.
String tempData = new SharedPrefsOperations(this).getPreferencesData("ActiveNotifs");
Notification notification = new NotificationCompat.Builder(this, "MYAPP")
.setSmallIcon(R.mipmap.ic_static_notif)
.setContentTitle(content.getTitle())
.setContentText(tempMsg)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setGroup(notifGroup)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setChannelId(channel_id)
.setStyle(inboxStyle)
.setGroupSummary(true)
.build();
notificationManager.notify(id, notification);
new SharedPrefsOperations(this).storePreferencesData("ActiveNotifs", "1");
} else {
// I AM EXECUTING THIS FROM SECOND NOTIFICATION ONWARDS
String tempData = new
SharedPrefsOperations(this).getPreferencesData("ActiveNotifs");
Notification notification = new NotificationCompat.Builder(this, "MYAPP")
.setSmallIcon(R.mipmap.ic_static_notif)
.setContentTitle(content.getTitle())
.setContentText(tempMsg)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setGroup(notifGroup)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setChannelId(channel_id)
.setStyle(inboxStyle)
.build();
notificationManager.notify(id, notification);
new SharedPrefsOperations(this).storePreferencesData("ActiveNotifs", "1");
}
If you are using same id for notifying, it won't work. You need to use a different id for that
Update
Above Android 8.0 (Oreo) Notification Channels are compulsory. So add the notification channel like this. This should be done before notifying.
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Android O requires a Notification Channel.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = context.getString(R.string.app_name)
// Create the channel for the notification
val mChannel = NotificationChannel("channel_id_sms", name, NotificationManager.IMPORTANCE_DEFAULT)
// Set the Notification Channel for the Notification Manager.
mNotificationManager.createNotificationChannel(mChannel)
}