I am implementing firebase push notification in my app, the app is showing the push notification also. But my problem is - I may send different types of push notifications based on different topics.
Ex -
1. If I am sending a push notification on App Update, then on clicking that notification by the user, he should be redirected to PlayStore
If I am sending a push notification on New Contents, then on clicking that notification by the user, he should be redirected to App's MainActivity
If I am sending a push notification on New Contest, then on clicking that notification by the user, he should be redirected to App's ContestActivity
I implemented it using the below code in "MessageReceiver" class as --
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
showNotifications(title, message);
}
private void showNotifications(String title, String msg) {
Intent i = null;
if(title.equals("DoUp Now - Update")){
Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=com.s2s.doupnow"); // missing 'http://' will cause crashed
i = new Intent(Intent.ACTION_VIEW, uri);
}
else if(title.equals("DoUp Now - New Content")){
i = new Intent(this, MainActivity.class);
}
else if(title.equals("DoUp Now - New Notification")){
i = new Intent(this, NotificationActivity.class);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, REQUEST_CODE,
i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder, mBuilderOld;
final int NOTIFICATION_ID = 1;
final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// 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);
mNotifyManager.createNotificationChannel(notificationChannel);
mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
mBuilder.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.doupnowlogo)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
}
else
{
mBuilderOld = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
mBuilderOld.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.doupnowlogo)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationManager.IMPORTANCE_MAX);
mNotifyManager.notify(NOTIFICATION_ID, mBuilderOld.build());
}
}
But on clicking any notification by the user, he is always redirected to App's MainActivity only.
Can anyone guide me where i am missing.
If you are comparing title using api the you have to check the title using JSON object like this.
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
Make sure the title you get is equal as title you are comparing and add flags in intent.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Related
I have Implemented heads up notification for my app. Code is like this:
private String CHANNEL_ID = "message_notifications";
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,"message_notifications", NotificationManager.IMPORTANCE_HIGH);
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String user_id = remoteMessage.getData().get("user_id");
String user_name = remoteMessage.getData().get("user_name");
String GROUP_KEY_CHIT_CHAT = "com.android.example.Chit_Chat";
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.chitchat_icon)
.setContentTitle(notification_title)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setGroup(GROUP_KEY_CHIT_CHAT)
.setDefaults(Notification.DEFAULT_ALL)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setContentText(notification_message);
if (Build.VERSION.SDK_INT >= 21) mBuilder.setVibrate(new long[0]);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", user_id);
resultIntent.putExtra("user_name",user_name);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
stackBuilder.addParentStack(MainActivity.class);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel.setShowBadge(true);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mNotificationManager.createNotificationChannel(mChannel);
mBuilder.setChannelId(CHANNEL_ID);
}
mNotificationManager.notify(mNotificationId,mBuilder.build());
}
Problem is It only works correctly when I do the settings for the notification as popup and sound else it appears like simple notification. Whatsapp and other applications are by default settuped to use them. I want to do the same. I want to programmatically set the settings for my app to use heads up notification by default without going into the setting to enable it. Can anybody help me how to do that?
I need to set it to sound and popup it doesn't set by default
Set the importance level of notification channel to IMPORTANCE_HIGH to appears as a heads-up notification.
Set notification as ongoing using setOngoing method if you want the notification dismissed only while performing an action. Ongoing notifications cannot be dismissed by the user, so your application or service must take care of canceling them.
If you want to show the notification in Do Not Disturb mode as well you can set category to CATEGORY_ALARM
If you want an intent to launch instead of posting the notification to the status bar for demanding the user's immediate attention use setFullScreenIntent
Sample code block
Intent launch = new Intent(context, TargetActivity.class);
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
launch, PendingIntent.FLAG_UPDATE_CURRENT);
createNotificationChannel(mContext, NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_HIGH,
R.string.notification_channel_name, R.string.notification_channel_description);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID);
builder.setContentTitle("Title");
builder.setContentText("Content Text");
builder.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Big Content Text"));
builder.setSmallIcon(R.drawable.status_icon);
builder.setFullScreenIntent(pendingIntent, true);
builder.setOngoing(true);
builder.setAutoCancel(true);
builder.setCategory(NotificationCompat.CATEGORY_ALARM);
builder.addAction(0, "Action Text", pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
notificationManager.notify(COMPLETE_NOTIFICATION_ID, builder.build());
/**
* create Notification channel
* #param context
* #param channelId
* #param channelName
* #param channelDescription
*/
#RequiresApi(api = Build.VERSION_CODES.O)
public static void createNotificationChannel(Context context, String channelId, int importance, int channelName, int channelDescription) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getString(channelName);
String description = context.getString(channelDescription);
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
I am building an app which shows notification when a new message arrives.I have successfully implemented the notification part-but there, I am facing some weird issue while viewing my shown notifications -it is showing different content text based on different scenarios-I am including the 2 cases-
a)when the notifications arrives
b)when I slide down the notification tray to see my notifications
As you can clearly see the differences in the content-text in two different cases- Why is it happening ?
I am attaching the code which I have implemented to build the notifications-
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String identifyDataType = remoteMessage.getData().get(getString(R.string.data_type));
//SITUATION: Application is in foreground then only send priority notificaitons such as an admin notification
Log.d(TAG, "Data type: data: " +identifyDataType);
if(identifyDataType.equals(getString(R.string.data_type_admin_broadcast))){
//build admin broadcast notification
String title = remoteMessage.getData().get(getString(R.string.data_title));
String senderId=remoteMessage.getData().get(getString(R.string.sender_of_message));
String message = remoteMessage.getData().get(getString(R.string.data_message));
Log.d(TAG,"TITL AND MESSG"+title+message);
sendBroadcastNotification(title, message,senderId);
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void sendBroadcastNotification(String title, String message, String senderId){
Log.d(TAG, "sendBroadcastNotification: building a admin broadcast notification with "+title+" "+message);
NotificationChannel mChannel=null;
// Instantiate a Builder object.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default_channel_id");
// Creates an Intent for the Activity
Intent notifyIntent = new Intent(this, MainActivity.class);
notifyIntent.putExtra("Id", "none");
Log.d("messsagingService Title",title);
notifyIntent.putExtra("Name", title.split(":")[1].trim());
// Sets the Activity to start in a new, empty task
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Creates the PendingIntent
PendingIntent notifyPendingIntent =
PendingIntent.getActivity(
this,
0,
notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mChannel = new NotificationChannel("default_channel_id", getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription(message);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
//add properties to the builder
builder.setSmallIcon(R.drawable.icons1)
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.icons1))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentTitle(title)
.setContentText(message)
.setColor(getResources().getColor(R.color.blue_btn_bg_color))
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(title).setSummaryText(message))
.setNumber(mNumPendingMessages)
.setOnlyAlertOnce(true);
builder.setContentIntent(notifyPendingIntent);
mNotificationManager.notify(BROADCAST_NOTIFICATION_ID, builder.build());
}
Any help is very much solicited -why this is even happening! Thank you.
We have created an chat app with notifications using FCM my code is correct my device is getting the push notification data as well but some Chinese manufactured device like vivo, oppo, one plus, xiaomi are not allowing the notification to show unless i add app in protected app list of respective manufacturer. is their any solution for this.
https://hackernoon.com/notifications-in-android-are-horribly-broken-b8dbec63f48a
https://github.community/t5/Project-Development-Help-and/Firebase-Push-Notification-not-receiving-on-some-android-devices/td-p/5489
private NotificationManagerCompat notificationManager;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("test","call");
notificationManager = NotificationManagerCompat.from(this);
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
private void sendNotification(String title, String msg) {
Intent resultIntent = new Intent(this, ActivitySplashScreen.class);
String channelId = getString(R.string.chc);
String channelName = "Message Notification";
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(99, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(msg)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.build();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager manager = getSystemService(NotificationManager.class);
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
notificationManager.notify(10, notification);
}
I can confirm that this implementation works well with One Plus and Xiaomi devices (we have plenty of users using our app from this devices, and no crashes or issues are created from them regarding FCM Notifications).
Cannot confirm anything for Vivo or Oppo (so far, we do know we don't have users using this kind of devices).
The most important thing is that the notification feature is well implemented if regarding the app is either in foreground or background. If someone wants to do a zoom on this matter, this article explains it on a easy way.
Now, the code I use for FCM implementation in Android:
//MyMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String TAG = "Firebase Msg";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
final LocalNotification localNotification = new LocalNotification();
//data --> entityId - entityType - pushNotificationType
// Check if message contains a data payload.
if (data.size() > 0) {
localNotification.setEntityId(data.get("entityId"));
localNotification.setEntityType(data.get("entityType"));
localNotification.setPushNotificationType(data.get("pushNotificationType"));
localNotification.setTitle(data.get("title"));
localNotification.setBody(data.get("body"));
localNotification.setIcon(data.get("icon"));
localNotification.setDate(new Date().getTime());
localNotification.setRead(false);
}
if (localNotification.getEntityId() != null) {
LocalNotification notificationRetrieved = FirebaseNotificationsHelper.insertLocalNotification(localNotification);
FirebaseNotificationsHelper.createNotificationInStatus(notificationRetrieved);
}
}
}
//Create notification status
static void createNotificationInStatus(LocalNotification localNotification) {
String notificationChannelId = App.getContext().getString(R.string.default_notification_channel_id);
String notificationChannelName = App.getContext().getString(R.string.default_notification_channel_name);
String notificationChannelDescription = App.getContext().getString(R.string.default_notification_channel_description);
NotificationCompat.Builder notificationBuilder;
NotificationCompat.Builder notificationBuilderPublicVersion;
notificationBuilder = new NotificationCompat.Builder(App.getContext(), notificationChannelId);
notificationBuilderPublicVersion = new NotificationCompat.Builder(App.getContext(), notificationChannelId);
notificationBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE | NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.DEFAULT_SOUND)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_stat_push_notif)
.setTicker(localNotification.getTitle())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(localNotification.getTitle())
.setContentText(localNotification.getBody())
.setStyle(new NotificationCompat.BigTextStyle().bigText(localNotification.getBody()))
.setPublicVersion(notificationBuilderPublicVersion.setSmallIcon(R.drawable.ic_stat_push_notif).setContentTitle(localNotification.getTitle()).
setWhen(System.currentTimeMillis()).setContentText(localNotification.getBody()).build())
.setGroup(NOTIFICATION_GROUP)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setAutoCancel(true);
int notificationId = SharedPreferencesUtils.getInstance(App.getContext()).getIntValue(PREF_KEY_NOTIFICATION_ID, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, notificationChannelName, NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription(notificationChannelDescription);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(notificationId, notificationBuilder.build());
} else {
/* Kitkat and previous versions don't show notifications using NotificationManagerCompat */
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notificationBuilder.build());
} else {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(App.getContext());
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
notificationId++;
SharedPreferencesUtils.getInstance(App.getContext()).setValue(PREF_KEY_NOTIFICATION_ID, notificationId);
}
I donot think that there is a general solution for this since your app is based on google-FCM that means that the android device regularly comunicates with google-internet-services.
As far as i know google-FCM is blocked (= not reachable) in china
I'm struggling to get my FCM notifications to stack in the same way as for Whatsapp:
1) The latest message for a particular room is displayed, with an updated count of all unread messages.
2) Indicating separate groupings of point 1 for notifications for different rooms.
I have spent a few hours looking at various SO questions and this is the closest I've come to finding an answer. The issue is that I am using a data payload, not notification, and it doesn't seem like the "tag" property works for my data payload.
The current behavior is that only the latest notification shows, overriding the previous.
Here is the sendNotification() method in my FirebaseMessagingService
private void sendNotification(RemoteMessage remoteMessage) {
//Intent intent = new Intent(this, StudentChatActivity.class);
String clickAction = remoteMessage.getData().get("click_action");
Intent intent = new Intent(clickAction);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
String roomID = remoteMessage.getData().get("ROOMID");
String origin = remoteMessage.getData().get("ORIGIN");
String msgID = remoteMessage.getData().get("MSGID");
Log.d(TAG, "Message data payload, roomID: " + roomID);
intent.putExtra("ROOMID", roomID);
intent.putExtra("USERID", UserID);
intent.putExtra("USERNAME", UserName);
intent.putExtra("ORIGIN", origin);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.received_message);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.small_pickle)
.setContentTitle("FCM Message")
.setContentText(remoteMessage.getData().get("body"))
.setPriority(1)
.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_HIGH);
notificationManager.createNotificationChannel(channel);
}
Log.d(TAG, "Noification ID: " + notify_no);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
I am working on an application which sends device to device push notification. I have created a custom notification layout which has a heading, message and two buttons (Accept and Reject). When device B receives a notification from Device A, for some phones it works perfectly, but in some phones the notification tray fails to display the title, message and buttons. It just shows a blank notification tray. Its not an error, but the custom layout doesn't load for some phones. It works perfectly in Moto G5s plus (Android 7.1.1), but doesn't work for RedMi Note 5 Pro, same API level (Android 7.1.1). Can anyone help me with this?
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> remoteMessageData = remoteMessage.getData();
String remoteMessageType = remoteMessageData.get("type");
String message = remoteMessageData.get("message") + ". Please Confirm?";
String profilePhoto = remoteMessageData.get("profile_photo");
String notificationUID = remoteMessageData.get("notification_uid");
String userUID = remoteMessageData.get("user_uid");
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_custom_notification);
remoteViews.setTextViewText(R.id.textNotificationMessage, message);
remoteViews.setImageViewBitmap(R.id.eIntercomProfilePic, getBitmapFromURL(profilePhoto));
Notification notification = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.namma_apartment_notification)
.setAutoCancel(true)
.setCustomBigContentView(remoteViews)
.setSound(RingtoneManager.getDefaultUri(Notification.DEFAULT_SOUND))
.setPriority(PRIORITY_DEFAULT)
.build();
int mNotificationID = (int) System.currentTimeMillis();
Intent acceptButtonIntent = new Intent("accept_button_clicked");
acceptButtonIntent.putExtra("Notification_Id", mNotificationID);
acceptButtonIntent.putExtra("Notification_UID", notificationUID);
acceptButtonIntent.putExtra("User_UID", userUID);
PendingIntent acceptPendingIntent = PendingIntent.getBroadcast(this, 123, acceptButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.buttonAccept, acceptPendingIntent);
Intent rejectButtonIntent = new Intent("reject_button_clicked");
rejectButtonIntent.putExtra("Notification_UID", notificationUID);
rejectButtonIntent.putExtra("Notification_Id", mNotificationID);
rejectButtonIntent.putExtra("User_UID", userUID);
PendingIntent rejectPendingIntent = PendingIntent.getBroadcast(this, 123, rejectButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.buttonReject, rejectPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/*To support Android Oreo Devices and higher*/
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
getString(R.string.default_notification_channel_id), "Namma Apartments Channel", NotificationManager.IMPORTANCE_HIGH);
Objects.requireNonNull(notificationManager).createNotificationChannel(mChannel);
}
}
i think you talking about Oreo or above version. Oreo can not support notification for notification you need to create channel for that like below :
private void sendMyNotification(String message,String title) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant")
NotificationChannel notificationChannel=new NotificationChannel("my_notification","n_channel",NotificationManager.IMPORTANCE_MAX);
notificationChannel.setDescription("description");
notificationChannel.setName("Channel Name");
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.listlogo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.tlogo))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationManager.IMPORTANCE_MAX)
.setOnlyAlertOnce(true)
.setChannelId("my_notification")
.setColor(Color.parseColor("#3F5996"));
//.setProgress(100,50,false);
notificationManager.notify(0, notificationBuilder.build());
}