I'm using Android O Emulator and want to get notification from Firebase console.It is working fine on every device except Android O. I'm getting this Error in Log.
W/Notification: Use of stream types is deprecated for operations other than volume control
W/Notification: See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case
I know that I have to specify Channel id for that .
So What I have done so far
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/attach" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="my_notification_channel" />
<service android:name=".Helper.FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".Helper.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<my all activities...>
I've also specify channel id in FirebaseMessagingService like this
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
private static final int NOTIFICATION_ID = 1;
private static final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title")
.setContentText(remoteMessage.getNotification().getBody())
.setOngoing(true)
.setChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
So after doing all this . I still got that error message in log and can't receive notification from console.Any Help would be appreciable.
When an FCM message contains no data payload, only a notification payload, and your app is in the background, Firebase generates the notification directly and does not call onMessageReceived(). This is explained in the documentation.
For Android O, a notification channel must be created. You are correctly defining the default notification channel in your manifest, but the channel is created in the onMessageReceived() code, which does not execute when the app is in the background.
Move the code that creates the channel somewhere that you can be certain it will execute before a notification is received.
Also, as indicated in the Firebase Release Notes, support for notification channels was added in version 10.2.6. You must build with at least that version.
Related
it's been weeks since i have this problem. i can already generate the FCM token and subscribe topics.
the problem that i am having is when i click the notification, nothing is happening it is not even going to the application and i still can't get the body and title of the notification. i know that the notification do not have a relationship with the actual application that i have, i already followed the documentation on handling the receive messages but still nothing is happening.
here is the link that i followed. https://firebase.google.com/docs/cloud-messaging/android/receive
Here is the code that i have.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
and here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eperformax.eplife">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
i already saw some related question here but nothing solves my problem. i just followed the documentation and still this is happening.
Can anyone help me this is really stressing me out. Any help would be really appreciated.
This question already has answers here:
Notification not showing in Oreo
(24 answers)
Closed 4 years ago.
I am setting up firebase push notification, and as per the documentation I did everything I guess
So what I did is from Tools > Firebase > Cloud Messaging added Dependencies see my gradle
implementation 'com.google.firebase:firebase-core:11.8.0'
implementation 'com.google.firebase:firebase-messaging:11.8.0'
implementation 'com.google.android.gms:play-services-ads:11.8.0'
After this I created a Class MyyFirebaseMessagingService and extended FirebaseMessagingService see below
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("RefreshedToken", "onMessageReceived: " + remoteMessage.getNotification().getBody());
showNotification(remoteMessage.getNotification().getBody());
}
private void showNotification(String message) {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Quotes App")
.setContentText(message)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
}}
After this I addeed Service in the manifest
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
And now when I try to send notification I dont receive it. What am I doing wrong
Create a channel and set the importance
Before you can deliver the notification on Android 8.0 and higher, you
must register your app's notification channel with the system by
passing an instance of NotificationChannel to
createNotificationChannel().
As the documentation say, you need to add a notification channel in android 8 and higher so the system shows your notification.
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
First of all, you need to create notification channel...and channel id should be between 1 to 10.
Secondly, upgrade to the latest version of libraries in app/gradle.build
If app is in the foreground (visible to user), onMessageReceived() is called.
If app is in the background (not visible to user), then, onMessageReceived() isn't called and notification is automatically shown to user, without you manually showing them...and data values are passed as intent extras to you launcher activity when clicked.
UPDATE 3: RESOLVED!
problem was not connected with FirebaseService, settings or payload. Problem was in application code... Our code had such thing (inheritance from Application):
ParentDroidApplication : Application
In that class in OnCreate method select which activity to use and Call "StartActivity". I moved this switch to MainActivity and problem was solved.
UPDATE 2:
Android Manifest (deleted service tag):
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.visma.vfsmobileparentapp" android:versionName="1.0" android:installLocation="internalOnly" android:versionCode="46">
<uses-sdk android:minSdkVersion="23" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="true" android:theme="#style/Theme.AppCompat.Light" android:label="Min skole" android:icon="#drawable/ic_launcher" android:name="Min skole">
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="#drawable/ic_launcher" />
</application>
</manifest>
Payload (added content_available and priority):
{
"to" : "token",
"collapse_key" : "type_a",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A"
},
"data" : {
"body" : "First Notification",
"title": "Collapsing A"
},
"content_available": true,
"priority": "high"
}
result same: app is opening automatically after remote notification :(
UPDATE:
I added intent with my main activity, default sounds and Miliseconds as int for notification number in OnMessaggeReceive method (you can see in the code below).
I tried to delete
<service android:name=".MyFirebaseMessagingService" android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
I didn't receive any notifications but app is still opening. it seems that Firebase is working as it should work. But application it self doing magic
I tried to downgrade Firebase to version 42.1021.1. Result is same
QUESTION
We are developing mobiles apps with Xamarin. We need notifications and we started to use Firebase Cloud messaging. All messages (notifications) are working, receiving, even updating badges in iOS, but... one problem with Android:
If app is closed (swiped from app list) and receiving remote notification it is opening automatically. I want to avoid this. Background or foreground modes are working as expecting.
My Andoroid manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app" android:versionName="1.0" android:installLocation="internalOnly" android:versionCode="46">
<uses-sdk android:minSdkVersion="23" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="true" android:theme="#style/Theme.AppCompat.Light" android:label="App" android:icon="#drawable/ic_launcher" android:name="App">
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="#drawable/ic_launcher" />
</application>
<service android:name=".MyFirebaseMessagingService" android:stopWithTask="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</manifest>
My FirebaseMessagingService.cs:
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
public override void OnMessageReceived(RemoteMessage message)
{
SendNotification("title", "body"); //just for testing
}
public void SendNotification(string title, string body)
{
var intent = new Intent(this, typeof(LoginActivity));
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
var style = new Android.Support.V4.App.NotificationCompat.BigTextStyle();
style.BigText(body);
Bitmap largeIcon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_launcher);
var notificationBuilder =
new Android.Support.V4.App.NotificationCompat.Builder(this)
.SetLargeIcon(largeIcon)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentTitle(title)
.SetContentText(body)
.SetStyle(style)
.SetAutoCancel(true)
.SetSound(defaultSoundUri)
.SetContentIntent(pendingIntent)
.SetVisibility((int)NotificationVisibility.Public);
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(DateTime.Now.Millisecond, notificationBuilder.Build());
}
}
I tried change manifest values, tried simulator, device, I sent different payloads:
both notification and data:
{
"to" : "token",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A"
},
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
}
}
only notification:
{
"to" : "token",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A"
}
}
only data:
{
"to" : "token",
"data" : {
"body" : "First Notification",
"title": "Collapsing A"
}
}
in all cases notification is receiving and opening app automatically when app is closed. How to avoid that auto opening? I need only notification. Any ideas what I can do?
nuget packages:
Xamaring.Firebase.Messaging - 60.1142.1
Xamarin.Firebase.Code - 60.1142.1
Xamarin.Firebase.Common - 60.1142.1
tested in Android 6 and Android 7 devices (Samsung)
You need to define here Activity, which has to open when you tap notification.
var intent = new Intent(this, typeof(YourActivity));
intent.AddFlags(ActivityFlags.ClearTop);
//sent RemoteMessage message data to your activity if you need
//intent.PutExtra("User", JsonConvert.SerializeObject(user));
var pendingIntent = PendingIntent.GetActivity(this, GenerateRandom(), intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Notification.Builder(this)
.SetSmallIcon(Resource.Drawable.myIcon)
.SetContentTitle(user.Organization)
.SetSubText(myModuleName)
.SetContentText(BodyText)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.Build();
var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
var notification = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
//this is for sound of notification
var mp = MediaPlayer.Create(ApplicationContext, notification);
mp.Start();
notificationManager.Notify(GenerateRandom(), notificationBuilder);
To just give unique Id to notifications so that they wont overlap
private int GenerateRandom()
{
var rn = new Java.Util.Random();
int n = 1000 - 1233 + 1;
int i = rn.NextInt() % n;
return 1000 + i;
}
My understanding of the situation tells me that since you have not given the notification a pending intent it is directly opening your application:
Workaround to this problem :
Intent intent = new Intent(this, typeof(MainAcitivity)); //Activity you want to open
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, RandomGenerator(), intent, PendingIntentFlags.OneShot);
In case you want default sounds :
Notification notify = new Notification();
notify.Defaults = NotificationDefaults.Sound;
notify.Defaults = NotificationDefaults.Vibrate;
Using the NotificationCompat to push the notification(For backward Compatibility)
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Drawable.Icon)
.SetContentTitle(messageTitle)
.SetContentText(messageBody)
.SetSound(Settings.System.DefaultNotificationUri)
.SetVibrate(new long[] { 1000, 1000 })
.SetLights(Color.AliceBlue, 3000, 3000)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
Then notifying the system that a notification is thrown from your application:
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(RandomGenerator(), notificationBuilder.Build());
Also, Random numbers so that the notifications don't switch places when a new one is thrown :
private int RandomGenerator()
{
return new Random().Next( int.MinValue, int.MaxValue );
}
And for Android Oreo channel compatibility as you can see official docs, you need to add the following metadata element in your AndroidManifest.xml within the application component:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
This default channel will be used when notification message has no specified channel, or if the channel provided has not yet been created by the app.
I have been having difficulties lately getting many specific functions to work on Android Studio. Recently I am working on trying to display simple notifications. They never show up. I feel like I have tried everything at this point. Here's my code.
public class NotificationReceiver extends BroadcastReceiver {
private final String TAG = NotificationReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, ScrollingActivity.class);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addParentStack(ScrollingActivity.class);
taskStackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(100, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "channel");
Notification notification = builder.setContentTitle("My Test Notification")
.setContentText("This is some sample test notification. (Congratulations!)")
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}}
Here's the method I use to call the notification.
public void setRepeatingNotification(){
Calendar repeatCalendar = Calendar.getInstance();
repeatCalendar.set(Calendar.HOUR_OF_DAY, 21);
repeatCalendar.set(Calendar.MINUTE, 40);
repeatCalendar.set(Calendar.SECOND, 10);
Intent intent = new Intent(ScrollingActivity.this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ScrollingActivity.this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, repeatCalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Toast.makeText(ScrollingActivity.this, "Repeating Notification Set", Toast.LENGTH_LONG).show();
}
Here's the manifest.
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="#mipmap/skillset_v3"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<activity
android:name=".ScrollingActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".TaskViewActivity"
android:label="#string/title_activity_task_view"
android:parentActivityName=".ScrollingActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.jermaineoliver.aswitch.ScrollingActivity" />
</activity>
<activity
android:name=".MasteryViewActivity"
android:label="#string/title_activity_mastery_view"
android:parentActivityName=".ScrollingActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.jermaineoliver.aswitch.ScrollingActivity" />
</activity>
<service
android:name="TaskTrackingService"/>
<receiver android:name=".NotificationReceiver"/>
</application>
Please help! I have been working on this forever.
It has to do with NotificationChannel. In Android Oreo and up you can create a NotificationChannel like this:
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = "my_channel_id";
CharSequence channelName = "My Channel";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{1000, 2000});
notificationManager.createNotificationChannel(notificationChannel);
Then you create your Notification as below:
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notifyId = 1;
String channelId = "my_channel_id";
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("My Message")
.setContentText("My test message!")
.setSmallIcon(R.drawable.ic_notification)
.setChannel(channelId)
.build();
notificationManager.notify(id, notification);
This way The notification will use the proper notification channel and will be displayed correctly. You can also create groups for notification channels. Read more here:
Documenation - NotificationChannel
Examples
Surprised no one jumped on this one. I found the answer. The API level was mismatched. Apparently NotificationChannel is required for Notifications using versions higher than Oreo. When I tried it on a lower API it worked. Knowing that kind of led my hand towards being able to get it to work. If anyone else has this problem let me know, maybe I can help.
I am checking Firebase Cloud Messaging to send notification. Have implemented it already and its receiving notification when app is in open state. But if I close app, its no longer gives notification. Is there any solution for this.
Code:
WebRequest wRequest;
wRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
wRequest.Method = "post";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));
string postData = "{\"registration_ids\":[\"" + regIds + "\"], \"data\": "+ value +"}";
Byte[] bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
WebResponse wResponse = wRequest.GetResponse();
Messaging service-
public class MessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
sendNotification(data);
}
public void showMessage(Map<String, String> serverData) {
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle(serverData.get("Title"))
.setContentText(serverData.get("Message"))
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(Integer.parseInt(serverData.get("ItemId")),builder.build());
}
private void sendNotification(Map<String, String> serverData) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);
long[] pattern = {500,500,500,500,500};
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle(serverData.get("Title"))
.setContentText(serverData.get("Message"))
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE,1,1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Integer.parseInt(serverData.get("ItemId")), notificationBuilder.build());
}
}
Main activity-
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseMessaging.getInstance().subscribeToTopic("test");
FirebaseInstanceId.getInstance().getToken();
}
}
Manifest-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.com.firebasenotify">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".InstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
There was no issue with the code. I was using Mi note 4, and somehow it does not show notification in Mi4 when app is closed. I tested with other android device and its working fine.
Thanks to Tim Castelijns and Frank van Puffelen for participating in the conversation.
There's good solution and explanation about that issue here. You need to set high priority for notification to tell android react immediately, otherwise it takes couple of minutes to display received notification.
I used Legacy Server Key instead of Server Key it had worked for me.
adding time_to_live key in your POST Payload will solve this problem.The value of this parameter must be a duration from 0 to 2,419,200 seconds, and it corresponds to the maximum period of time for which FCM stores and attempts to deliver the message. "time_to_live" : 3 Refer Firebase Docs
As per FCM docs onMessageReceived() won't be called when app is in the background. You should send a notification object on order to show it up in the system tray and when user clicks it the launcher activity will be open with data as extras with the intent. For payloads you should use data object. see docs and Receive Messages in an Android App