Notification not received in android API eval 26 [duplicate] - android

This question already has answers here:
Notification not showing in Oreo
(24 answers)
Closed 4 years ago.
I try to receive notification in android Oreo. But App does not receive any
notification. I also create notification Chanel but it's not work
If I send a notification from fcm then app received. but using the token app not received any notification. In other lower, version notification work proper. In Oreo it does not work.
Here is my MyFirebaseMessagingService class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
public static final String NOTIF_CHANNEL_ID = "my_channel_01";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getData());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotifChannel(this);
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void createNotifChannel(MyFirebaseMessagingService
myFirebaseMessagingService)
{
NotificationChannel channel = new NotificationChannel(NOTIF_CHANNEL_ID,
"MyApp events", NotificationManager.IMPORTANCE_LOW);
// Configure the notification channel
channel.setDescription("MyApp event controls");
channel.setShowBadge(false);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = getApplicationContext().
getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
Log.d(TAG, "createNotifChannel: created=" + NOTIF_CHANNEL_ID);
}
private void sendNotification(Map<String, String> data) {
int num = ++NOTIFICATION_ID;
Bundle msg = new Bundle();
for (String key : data.keySet()) {
Log.e(key, data.get(key));
msg.putString(key, data.get(key));
}
Intent intent = new Intent(this, HomeActivity.class);
if (msg.containsKey("action")) {
intent.putExtra("action", msg.getString("action"));
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, num /*
Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(instauser.application.apps.R.drawable.icon)
.setContentTitle(msg.getString("title"))
.setContentText(msg.getString("msg"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(num, notificationBuilder.build());
}
}
I also create a notification channel but it's not work

You created notification channel, but didn't set it to notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
...
.setChannelId(NOTIF_CHANNEL_ID)

Related

Unable to received notification in device notification section in android

This is my code to receive notification
public class FirebaseMessageReceiver
extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageTitle,String messageBody) {
Intent intent = new Intent(this, NotificationActivity.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.ic_launcher_background)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE,1,1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
i am trying to received notification from firebase console i am able to get to get call back when fire notification i am also getting title and msg code executed successfully but i am unable to see notification in notification section of device can any one please help me what i am doing mistake .
Do you use notification channel?
If you are using Adroid 8 or higher it's expected behavior:
Starting in Android 8.0 (API level 26), all notifications must be
assigned to a channel or it will not appear.
https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels
Here you can find detail tutorial how to create notification channel:
https://developer.android.com/training/notify-user/channels
For devices running Android O or higher, you need to create a notification channel first in order to receive notifications like this:
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel.setDescription("This is Channel 1");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
Also, you need to pass this CHANNEL_ID constant in NotificationCompact.Builder constructor like this:
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this, CHANNEL_ID)

Construct Notification for Xamarin Android Application

Am trying to create a notification that will notify user when alarm matures, am calling the Notification code in my OnCreate method, so i expect to see it when i launch my Activity but my code here seems to have a problem, any help to get the App to notify will greatly be appreciated...
Here is what i got so far
class SecondActivity : AppCompatActivity
{
static readonly int mid = 1000;
static readonly string CHANNEL_ID = "location_notification";
protected override void OnCreate(Bundle onSavedInstanceState){
//Notification code
NotificationChannel channel = null;
Intent intent=new Intent(this, typeof(SecondActivity));
//Construct TaskStack builder for pending intent
Android.App.TaskStackBuilder taskStackBuilder = Android.App.TaskStackBuilder.Create(this);
//Add intent to backstack
taskStackBuilder.AddNextIntentWithParentStack(intent);
//Construct pending intent to open desired activity
PendingIntent pendingIntent = taskStackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
//Enque notification to inform the user that the alarm has matured
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Drawable.abc_tab_indicator_mtrl_alpha)
.SetContentTitle("Alarm")
.SetContentIntent(pendingIntent);
.SetContentText("Alarm Time has matured");
NotificationManager notificationManager =
(NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.Notify(mid, mBuilder.Build());
channel = notificationManager.GetNotificationChannel(channelName);
notificationManager.CreateNotificationChannel(channel);
}
}
What Am i doing wrong?, Thanks
am calling the Notification code in my OnCreate method
You could not call notification on OnCreate method directly. Generaly We will use button click event or another separated task event to call Notification.
Second, as SushiHangover's said, you need to CreateNotificationChannel before publish
local notification.
You can refer to Notification channels to add notification channel:
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 channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel(CHANNEL_ID, channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager) GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
And pulish notification:
// Instantiate the builder and set notification elements:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetContentTitle ("Sample Notification")
.SetContentText ("Hello World! This is my first notification!")
.SetSmallIcon (Resource.Drawable.ic_notification);
// Build the notification:
Notification notification = builder.Build();
// Get the notification manager:
NotificationManager notificationManager =
GetSystemService (Context.NotificationService) as NotificationManager;
// Publish the notification:
const int notificationId = 0;
notificationManager.Notify (notificationId, notification);
Note: The CHANNEL_ID should be the same both on creating channel and publishing notification. Generally, we will use the package name as the channel id.
The full sample code as follows:
private void Button_Click(object sender, EventArgs e)
{
// create notification channel
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 channelName = "Notify user";
var channelDescription = "first local notification";
var channel = new NotificationChannel("com.companyname.appandroidlistview", channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "com.companyname.appandroidlistview")
.SetContentTitle("Sample Notification")
.SetContentText("Hello World! This is my first notification!")
.SetSmallIcon(Resource.Drawable.icon);
// Build the notification:
Notification notification = builder.Build();
// Get the notification manager:
NotificationManager notificationManager =
GetSystemService(Context.NotificationService) as NotificationManager;
// Publish the notification:
const int notificationId = 0;
notificationManager.Notify(notificationId, notification);
}
You need to do a lot of things before your notification can work, Microsoft documentation provides a very easy way of doing that...
class SecondActivity : AppCompatActivity
{
//Declare notification ID and Channel ID In your class so you can use them from any method
static readonly int NOTIFICATION_ID = 1000;
static readonly string CHANNEL_ID = "location_notification";
protected override void OnCreate(Bundle savedInstanceState){
}
//Define the method you will use to call notification
}
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 name = Resources.GetString(Resource.String.channel_name);
var description = GetString(Resource.String.channel_description);
var channel = new NotificationChannel(CHANNEL_ID, name, NotificationImportance.Default)
{
Description = description
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
//Use a button to send the notification to the operating system
private void notifier(object sender, EventArgs e){
Intent intent=new Intent(this, typeof(SecondActivity));
//Construct TaskStack builder for pending intent
Android.App.TaskStackBuilder taskStackBuilder = Android.App.TaskStackBuilder.Create(this);
//Add intent to backstack
taskStackBuilder.AddNextIntentWithParentStack(intent);
//Construct pending intent to open desired activity
PendingIntent pendingIntent = taskStackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
//Enque notification to inform the user that the alarm has matured
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.abc_tab_indicator_mtrl_alpha)
.SetContentTitle("Alarm")
.SetContentText("Alarm Time has matured")
.SetShowWhen(false).SetContentIntent(pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(NOTIFICATION_ID, mBuilder.Build());
}
}
}
If you follow the instructions on this page then your notification should show without so much hassle
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/notifications/local-notifications-walkthrough

Cannot resolve Method "builder()"

I want to send notifications to topics with FCM without using the Firebase console. When I build a new message with the help of Firebase Documentation it´s a problem.
Picture of the problem
Here my Codes:
public void sendToTopic() {
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setTopic("1")
.build();
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
public void onMessageReceived(RemoteMessage remoteMessage) {
}
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 = ("asda");
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.book_icon)
.setContentTitle("Test")
.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());
}
}
The Message class is inside the Firebase admin sdk but you cannot use that in your android project, you can only use firebase admin sdk in the server side and there you will be able to use the Message class. Check the docs for reference:-
https://firebase.google.com/docs/cloud-messaging/manage-topics

Android| Java Notifications not appearing in API 25 and lower

I have a firebase push notifications that sends text messages. My notifications appear in API 26 onward, but on APIs lower, (currently testing with API 22) and the messages are successfully sent, but they dont appear on the (API 22) device. What could be the problem?
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
createNotificationChannel();
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String dataMessage = remoteMessage.getData().get("message");
String dataFrom = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setPriority(NotificationCompat.PRIORITY_HIGH);
Intent intent = new Intent(click_action);
intent.putExtra("message", dataMessage);
intent.putExtra("from_user_id", dataFrom);
PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, builder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Personal Notifications";
String desc = "Include all the personal notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(getString(R.string.default_notification_channel_id), name, importance);
notificationChannel.setDescription(desc);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
What could be the problem?
If you have situation, when notification appears in status bar, but a floating window not popping up, you should add in your NotificationCompat.Builder
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
because such notifications are called a heads-up notifications and it should have high priority and use ringtones or vibrations on devices running Android 7.1 (API level 25) and lower
The issue is you have targeted Oreo and above in your createNotificationsChannel.
Exact place you target oreo and above is:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
The reason why this has happened will be because of the code listed below since it was added in API level 26. You will need to find an alternative version for lower levels.
notificationManager.createNotificationChannel(notificationChannel);
I had this a while ago. Keep your createNotificationChannel() method in your main class. However, I suggest creating a different class with a static method (to create your notification) then just call it in the FirebaseMessagingService class. Try this:
public class NotificationHelper {
public static void displayNotification(Context context,String title,String body){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,CHANNELID)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(1,mBuilder.build());
}
}
Then in your FMService class, just call the static method after your notification channel like so:
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
createNotificationChannel();
if(remoteMessage.getNotification()!=null){
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
NotificationHelper.displayNotification(getApplicationContext(),messageTitle,messageBody);
}
You should be fine.

Java Notification with a PendingIntent and putExtra don't work

I have a FireBase Message. If it comes in, I show a Notification (works). When I click on the Notification it should open my application (works). Now I want to use putExtra(), to hand over some information to my app (that works only sometimes - if the app is in the foreground). That's my problem.
private void sendMyNotification(String message) {
int rndNo4Intent = Math.round((float)(Math.random()*100000000));
int rndNo4Msg = Math.round((float)(Math.random()*100000000));
//On click of notification it redirect to this Activity
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("action","openWiki"+rndNo4Msg); // My Test-Data
PendingIntent pendingIntent = PendingIntent.getActivity(this, rndNo4Intent , intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String channelId = getString(R.string.default_notification_channel_id);
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("CodingSpace")
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
// Since android Oreo notification channel is needed. Sonst kommt nichts an.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"CodingSpaceChannel",
NotificationManager.IMPORTANCE_HIGH); // in Oreo ist High so, dass es einen Ton gibt
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(rndNo4Msg, notificationBuilder.build());
}
In the .MainActivity-Class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Intent iin= getIntent();
String msg = iin.getStringExtra("action");
Toast.makeText(MainActivity.this,"get: "+ msg,Toast.LENGTH_SHORT).show();

Categories

Resources