I'm trying do send a push notification to my android emulator. When the notification is sent, it receives the notification but does not display it.
I'm using this code to display it.
void SendNotification(string messageBody)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.SetContentTitle("FCM Message")
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(messageBody)
.SetChannelId("my-chanel")
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.SetSound();
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
But when the notification is received nothings happens and the logs of my devices gives me this:
[Mono] Assembly Ref addref ODEON.Android[0xa31db5c0] -> System.Core[0xa1f2f900]: 7
[MyFirebaseMsgService] From: 241571420247
[MyFirebaseMsgService] noti:
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for 'java_interop_jnienv_call_boolean_method'.
[Mono] Probing 'java_interop_jnienv_call_boolean_method'.
[Mono] Found as 'java_interop_jnienv_call_boolean_method'.
[Mono] Assembly Ref addref Xamarin.Android.Support.Compat[0xa31dca60] -> Java.Interop[0xa1f2f780]: 8
[Notification] Use of stream types is deprecated for operations other than volume control
[Notification] See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case
Can anyone tell my why it doesn't display.
Thanks in advance!
If the send notification mehtod is called use the below code to show notifications:
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
.SetContentTitle("Title")
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(0, notificationBuilder.Build());
Also if you have Android V 8+ devices which I'm sure you will see to it you are registering for a notification channel in your MainActivity OnCreate method
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channel = new NotificationChannel(CHANNEL_ID, "FCM Notifications", NotificationImportance.Default)
{
Description = "Firebase Cloud Messages appear in this channel"
};
var notificationManager = (NotificationManager) GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
Related
I have a Notification Hub in Azure to send PUSH to Android and iOS devices. Everything is working well in Android. In iOS I have this problem:
I turn off the WiFi or I turn off the device
I send chat messages to my app (push notifications) and also messages to that device from WhatsApp.
I turn on the WiFi or turn on the device after a few minutes
I receive all the WhatsApp messages notifications but no one of the notification to my App. If the device and Internet is on, I receive the notifications without problem.
My question is: Anyone has experienced something like that or know how to fix it?
At least I should have to receive the last push, right?
I'm sending the push to a tag. I can see the Device registered in the hub either when WiFi or iPhone are off.
When sending notification ensure that you set the expiration. Default value is zero. Hence, APNs treats the notification as if it expires immediately and does not store the notification or attempt to redeliver it.
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html
apns-expiration
If this value is nonzero, APNs stores the notification
and tries to deliver it at least once, repeating the attempt as needed
if it is unable to deliver the notification the first time. If the
value is 0, APNs treats the notification as if it expires immediately
and does not store the notification or attempt to redeliver it.
If you are using template notifications, here is how you do it.
AppleTemplateRegistrationDescription registration = new AppleTemplateRegistrationDescription(parameters.registrationID)
{ BodyTemplate = new CDataMember("{\"aps\":{\"alert\":\"$(body)\",\"payload\":\"$(payload)\",\"deeplinking\":\"$(deeplinking)\",\"category\":\"$(category)\",\"image\":\"$(image)\"}}"),
Tags = itags,
Expiry = "$(APNS_Expiry)"
};
As part of send, you can pass the expiry value.
var notification = new TemplateNotification(new Dictionary<string, string>()
{
{"APNS_Expiry", DateTime.UtcNow.AddMinutes(10).ToString("o") }, //Timestamp
{"body", NotificationText},
{"payload", NotificationText},
{"deeplinking", payload},
});
var Responsehub = hub.SendNotificationAsync(notification);
If you are using native notifications,
// Native notification
var notification = new AppleNotification(#"
{
""aps"": {
""alert"":""New notification!""
}
}");
notification.Expiry = DateTime.UtcNow.AddMinutes(2);
await notificationHubClient.SendNotificationAsync(notification);
If you are using template notifications, here is how you do it.
AppleTemplateRegistrationDescription registration = new AppleTemplateRegistrationDescription(parameters.registrationID)
{ BodyTemplate = new CDataMember("{\"aps\":{\"alert\":\"$(body)\",\"payload\":\"$(payload)\",\"deeplinking\":\"$(deeplinking)\",\"category\":\"$(category)\",\"image\":\"$(image)\"}}"),
Tags = itags,
Expiry = "$(APNS_Expiry)"
};
As part of send, you can pass the expiry value.
var notification = new TemplateNotification(new Dictionary<string, string>()
{
{"APNS_Expiry", DateTime.UtcNow.AddMinutes(10).ToString("o") }, //Timestamp
{"body", NotificationText},
{"payload", NotificationText},
{"deeplinking", payload},
});
var Responsehub = hub.SendNotificationAsync(notification);
If you are using native notifications,
// Native notification
var notification = new AppleNotification(#"
{
""aps"": {
""alert"":""New notification!""
}
}");
notification.Expiry = DateTime.UtcNow.AddMinutes(2);
await notificationHubClient.SendNotificationAsync(notification);
Iam trying to make a simple app for my raspberry pi that will send a message to the IOThub and then try to receive a response however nothing is happening.
I copied the connectionstring from the device controller. Ofcource I hidden it for this question.
I see it printing out that the message was succesfully sended to the iothub but when I check the iothub I see 0 received messages.
Iam using the free tier of the iothub is this a limitation?
public sealed partial class MainPage : Page
{
private const string DeviceConnectionString = "Hidden";
private readonly DeviceClient _deviceClient;
public MainPage()
{
this.InitializeComponent();
_deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Amqp); //Already tried using different transport types but no succes.
}
public async Task SendEvent()
{
Debug.WriteLine("\t{0}> Sending message", DateTime.Now.ToLocalTime());
var commandMessage = new Message(Encoding.ASCII.GetBytes("Cloud to device message."));
await _deviceClient.SendEventAsync(commandMessage);
Debug.WriteLine("Succesfully sended message to IotHub");
}
public async Task ReceiveCommands()
{
Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n");
while (true)
{
var receivedMessage = await _deviceClient.ReceiveAsync();
if (receivedMessage != null)
{
var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);
var propCount = 0;
foreach (var prop in receivedMessage.Properties)
{
Debug.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value);
}
await _deviceClient.CompleteAsync(receivedMessage);
Debug.WriteLine("Finishing recieving message");
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
private async void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
Debug.WriteLine("Sending event");
await SendEvent();
await ReceiveCommands();
Debug.WriteLine("Received commands");
}
}
It is nothing to do with free tier of the iothub. There is no such limitation.
You can't receive Device-To-Cloud(D2C) messages using DeviceClient that you used in ReceiveCommands(). It is by designed. You look like having some misunderstanding of Azure IoT Hub message types and SDKs.
There are two kinds of message types: Device-To-Cloud(D2C) message and Cloud-To-Device(C2D) message.
And two kinds of SDKs: device SDK and service SDK.
Device SDK is used to connect to and send D2C messages to Azure IoT Hub.
While service SDK is used to manage and send C2D messages to devices.
So, if you send C2D messages to device in Device Explorer you will receive these messages in your ReceiveCommands method.
If you want to receive D2C message you can utilize Event Hub-compatible endpoint(messages/events). Here is a console sample you can reference. But this is can't be done in UWP due to service bus not supported in UWP.
I am written code to send push notification to windows phone 8 by azure notification hub.
i am able to send to the toast notification to windows phone 8 and windows phone 8 also able to get notification . but when i am sending tile notification, it is sending tile notification successfully, but windows phone 8 is not getting this tile notification.
i already used BindToShellTile and BindToShellToast at the time of getting the channel Uri and after that i am doing the registration by this channel uri and checked IDCAPPUSH_NOTIFICATION the capabilities in windowsphone porject manifest to allow the push notification.
Below my Code for Bind the Device to Tile And Toast.
public void GetNotificationChannel()
{
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
// The name of our push channel.
string channelName = "ToastChannel";
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast and tile notifications.
pushChannel.BindToShellToast();
pushChannel.BindToShellTile();
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
//MessageBox.Show(String.Format("Channel Uri is {0}",
// pushChannel.ChannelUri.ToString()));
}
}
Below Code is sued to registered this device in notification hub.
// notification tois nothing but channel uri
private static async void WindowsPhoneRegistrations(string notificationToken)
{
try
{
var notificationHub = GetNotificationHubClient();
// this wil retunr the notification hub client by using the notificationconnectionstring // and hub path
var windowsPhoneRegistrationDescription = await notificationHub.CreateMpnsNativeRegistrationAsync();
}
catch (Exception ex)
{
throw;
}
}
Below code is for sending the tile notification
private static async void SendWindowsPhone8ToastNotification()
{
try
{
string windowsPhone8ToastFinalTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\" Version=\"2.0\">" +
"<wp:Tile Id=\"txt1\" Template=\"IconicTile\">" +
"<wp:SmallIconImage>http://flyosity.com/images/_blogentries/networkicon/step2.png</wp:SmallIconImage>" +
"<wp:IconImage>http://flyosity.com/images/_blogentries/networkicon/step2.png</wp:IconImage>" +
"<wp:WideContent1 >This is sample</wp:WideContent1>" +
"<wp:Count >1</wp:Count>" +
"<wp:Title >Good</wp:Title>" +
"</wp:Tile>" +
"</wp:Notification>";
var notificationHub = GetNotificationHubClient();
NotificationOutcome n = await notificationHub.SendMpnsNativeNotificationAsync(HttpUtility.HtmlEncode(windowsPhone8ToastFinalTemplate));
}
catch (Exception ex)
{
throw;
}
}
I am able to send the tile notification to notification hubs with out any exceptions and getting the status from notification hub after sending . but device is not getting the tile notification.
what i missed out or did mistake somewhere in this code to get the tile notification in windows phone 8. please help.
I have a link http://yousite/sample.mp3 and I want to pass it to default audio player in android:
I'm doing:
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType("audio/mp3");
startActivity(intent);
and it says:
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW typ=audio/mp3 }
if I omit intent.setType("audio/mp3"); it opens in the Browser with audio player in it which is clearly not what I want. I then tried to share:
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
and there was no application found to share to!
i am using windows azure Service Bus Notification Hubs for ios
i register my device by following code :
SBNotificationHub* hub = [[SBNotificationHub alloc] initWithConnectionString:
#"Endpoint=sb://......" notificationHubPath:#"...."];
NSMutableSet *set = [NSMutableSet set];
[set addObject:#"general"];
[hub registerNativeWithDeviceToken:deviceToken tags:[set copy] completion:^(NSError* error) {
if (error != nil) {
NSLog(#"Error registering for notifications: %#", error);
[self.delegate homePopUpViewControllerEnterButtonPress:self];
}
}];
and sending Notification from .Net Backend by using following code :
var hubClient = NotificationHubClient.CreateClientFromConnectionString(<connection string>, "<notification hub name>");
IDictionary<string, string> properties = new Dictionary<string, string>();
properties.Add("badge", "1");
properties.Add("alert", "This is Test Text");
properties.Add("sound", "bingbong.aiff");
hubClient.SendTemplateNotification(properties, "general");
i able to receive notification but my problem is : notification does not have any property that i added , no sound , no badge ...
if you can please help me
references : http://msdn.microsoft.com/en-US/library/jj927168.aspx
thanks
You registered for native notifications but then you are sending a template notification.
If you want to send native (this will require additional sends if you want to reach devices on different platforms) you have to use
hub.SendAppleNativeNotification(
"{ \"aps\": { \"alert\": \"This is my alert message for iOS!\"}}", "tag");
Please refer to https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html for the iOS payload format.
Alternatively, you can register for template notifications with:
NSString* template = #"{aps: {alert: \"$(myToastProperty)\"}}";
[hub registerTemplateWithDeviceToken:deviceToken
name:#"myToastRegistration"
jsonBodyTemplate:template
expiryTemplate:nil
tags:nil
completion:^(NSError* error) {
if (error != nil) {
NSLog(#"Error registering for notifications: %#", error);
}
}];
Using a template like:
{
“aps”: {
“alert”: “$(alert)”
}
}
Then you can send notifications using hub.SendTemplateNotification like you are already doing.
For more information regarding the difference between template and native please refer to: http://msdn.microsoft.com/en-us/library/jj927170.aspx