android-gcm | GCM Sample Client and Server | Microservice library
kandi X-RAY | android-gcm Summary
Support
Quality
Security
License
Reuse
- Initialize the registry
- Send registration id to server
- Called when a notification is received
- Prepares a notification
- Called when the registration is registered
- Called when the activity is created
- Reset the text to be resumed
- Displays an error message
- Called when the registration is unregistered
android-gcm Key Features
android-gcm Examples and Code Snippets
Trending Discussions on android-gcm
Trending Discussions on android-gcm
QUESTION
I have Notification Hub setup correctly with FCM and my Android app. The problem is when my app is in foreground the notification never shows but debugger catches on OnPushNotificationReceived so I know the setup is working. Also when the app is backgrounded or not running the notification pops up. I think it has to do with the code which I got from: https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm
Here is my code:
public void OnPushNotificationReceived(Context context, INotificationMessage message)
{
var intent = new Intent(context, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID);
notificationBuilder.SetContentTitle(message.Title)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentText(message.Body)
.SetAutoCancel(true)
.SetShowWhen(false)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManager.FromContext(context);
notificationManager.Notify(0, notificationBuilder.Build());
}
Any help would be much appreciated
ANSWER
Answered 2021-Aug-09 at 12:18I found the issue to be because no NotificationChannel existed so I created it in the contrstructor:
public AzureListener()
{
var channel = new NotificationChannel(MainActivity.CHANNEL_ID, "General", NotificationImportance.Default);
var notificationManager = NotificationManager.FromContext(Application.Context);
notificationManager.CreateNotificationChannel(channel);
}
It worked after I added this.
QUESTION
I am following this tutorial to test out notification hub for android and it works https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm
but I need to finish the user registration process and get the userid so I can use the userid as tag to register on Azure Notification hub. So instead of doing the registration right away in MainAcitivty.cs
, I just save the token in database.
so instead of having this
public override void OnNewToken(string token)
{
Log.Debug(TAG, "FCM token: " + token);
SendRegistrationToServer(token);
}
i just insert the token to local database
public override void OnNewToken(string token)
{
Log.Debug(TAG, "FCM token: " + token);
LocalDb.InsertDeviceToken(token);
}
when the whole registration process is finished, I have following in an RegistrationAcitivty.cs
var notificationUtil = new NotificationUtil();
notificationUtil.SendRegistrationToServer(this.ApplicationContext);
following is the code for NotificationUtil.cs
using System;
using System.Collections.Generic;
using Android.Util;
using PantAppLib.source.dbaccess;
using PantAppLib.source.models;
using WindowsAzure.Messaging;
namespace PantAppAndroid.Utils
{
public class NotificationUtil
{
public void SendRegistrationToServer(Android.Content.Context context)
{
try
{
// Register with Notification Hubs
NotificationHub hub = new NotificationHub(Constants.NotificationHubName,
Constants.ListenConnectionString, context);
var userProfile = LocalDb.GetUserProfile();
if (userProfile != null)
{
var tags = new List() { userProfile.Id };
var token = LocalDb.GetDeviceToken().TokenValue;
Registration registration = hub.Register(token, tags.ToArray());
var regID = registration.RegistrationId;
Log.Debug("MyFirebaseMsgService", $"Successful registration of ID {regID}");
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I can only guess that I am using the correct context object here, and when I run the code, i hit on following exception
{Android.OS.NetworkOnMainThreadException: Exception of type 'Android.OS.NetworkOnMainThreadException' was thrown.
at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in <42748fcc36b74733af2d9940a8f3cc8e>:0
at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualObjectMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <42748fcc36b74733af2d9940a8f3cc8e>:0
at WindowsAzure.Messaging.NotificationHub.Register (System.String pnsHandle, System.String[] tags) [0x00043] in <7ef3a358b177460dacd73e56198bd8f2>:0
at PantAppAndroid.Utils.NotificationUtil.SendRegistrationToServer (Android.Content.Context context) [0x00041] in C:\Users\weiha\source\repos\App2\PantAppAndroid\Utils\NotificationUtil.cs:36
--- End of managed Android.OS.NetworkOnMainThreadException stack trace ---
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
at java.net.InetAddress.getAllByName(InetAddress.java:1154)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:26)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:213)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:170)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:130)
at com.microsoft.windowsazure.messaging.NotificationHub.refreshRegistrationInformation(NotificationHub.java:301)
at com.microsoft.windowsazure.messaging.NotificationHub.registerInternal(NotificationHub.java:399)
at com.microsoft.windowsazure.messaging.NotificationHub.register(NotificationHub.java:148)
at mono.android.view.View_OnClickListenerImplementor.n_onClick(Native Method)
at mono.android.view.View_OnClickListenerImplementor.onClick(View_OnClickListenerImplementor.java:30)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
}
the follow up tutorial - Send notifications to specific devices is not for xamarin android, so i am not sure how to do it in a correct way.
ANSWER
Answered 2020-Sep-29 at 20:27The NetworkOnMainThreadException
is the key, looking at the exception stack, the NotificationHub.Register
is your problem as it can not be performed on the UI thread due to the underlaying networks calls that happen, just execute it on a background thread.
Example:
~~~
Registration registration;
await Task.Run(() => registration = hub.Register(token, tags.ToArray()));
~~~
QUESTION
I'm following the instructions on this page to create the push notifications. I've actually done it once before and was able to get it to work (a few weeks back), took some time away, and figured I'd do the tutorial again as a refresher only now, for some reason, I can't even get the code to hit the OnNewToken method to generate my token and register the device with the notification hub.
I've watched dozens of videos, read other tutorials, and they're all saying / showing pretty much the same thing so I think I need a new pair of eyes to show me what I'm missing this 2nd time around.
I've tried to pull out specific information but still keep it as readable as I could.
Installed NuGet packages:
- Xamarin.Firebase.Messaging - v71.1740.0
- Xamarin.GooglePlayServices.Base - v71.1610.0
- Xamarin.Forms - v4.4.0.991640
Files in Android project
AndroidManifest.xml
AppConstants
public static class AppConstants
{
public static string NotificationChannelName { get; set; } = "XamarinNotifyChannel";
public static string NotificationHubName { get; set; } = "(my azure notification hub name)";
public static string ListenConnectionString { get; set; } = "(my default listen shared access signature from azure portal)";
public static string DebugTag { get; set; } = "XamarinNotify";
public static string[] SubscriptionTags { get; set; } = { "default" };
public static string FCMTemplateBody { get; set; } = "{\"data\":{\"message\":\"$(messageParam)\"}}";
public static string APNTemplateBody { get; set; } = "{\"aps\":{\"alert\":\"$(messageParam)\"}}";
}
FirebaseService
[Service(Name = "(my package name).MyFirebaseMessagingService")]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class FirebaseService : FirebaseMessagingService
{
public override void OnNewToken(string token)
{
base.OnNewToken(token);
Console.WriteLine("NEW_TOKEN", token);
SendRegistrationToServer(token);
}
void SendRegistrationToServer(string token)
{
NotificationHub hub = new NotificationHub(AppConstants.NotificationHubName, AppConstants.ListenConnectionString, this);
// register device with Azure Notification Hub using the token from FCM
Registration reg = hub.Register(token, AppConstants.SubscriptionTags);
// subscribe to the SubscriptionTags list with a simple template.
string pnsHandle = reg.PNSHandle;
hub.RegisterTemplate(pnsHandle, "defaultTemplate", AppConstants.FCMTemplateBody, AppConstants.SubscriptionTags);
}
public override void OnMessageReceived(RemoteMessage message)
{
base.OnMessageReceived(message);
string messageBody = string.Empty;
if (message.GetNotification() != null)
{
messageBody = message.GetNotification().Body;
}
else
{
messageBody = message.Data.Values.First();
}
try
{
MessagingCenter.Send(messageBody, "Update");
}
catch (Exception e)
{ }
SendLocalNotification(messageBody);
}
void SendLocalNotification(string body)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
intent.PutExtra("message", body);
//Unique request code to avoid PendingIntent collision.
var requestCode = new Random().Next();
var pendingIntent = PendingIntent.GetActivity(this, requestCode, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this)
.SetContentTitle("XamarinNotify Message")
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentText(body)
.SetAutoCancel(true)
.SetShowWhen(false)
.SetContentIntent(pendingIntent);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
notificationBuilder.SetChannelId(AppConstants.NotificationChannelName);
}
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
}
google-services.json
I just downloaded this file from Firebase, added it to the Android project and set the Build Action to GoogleServicesJson.
Hopefully somebody can see what I'm missing as I've had this same tutorial working before.
ANSWER
Answered 2020-Feb-24 at 13:11You forgot [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
[Service()]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class FirebaseService : FirebaseMessagingService
{
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install android-gcm
You can use android-gcm like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the android-gcm component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page