I am using FCM to send notifications between users when they receive a new message.
I had like to make a group notification from my app so it will show like this:
However, for some reason every new notification that I get, it deletes the other so it always shows only the latest notification.
My code is:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private FirebaseAuth auth;
private FirebaseFirestore db;
private static String GROUP_KEY = "NOTIFICATION";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
createNotificationChannel();
notifyThis(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"),remoteMessage.getData().get("var1"),remoteMessage.getData().get("var2"),remoteMessage.getData().get("var3"));
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "ABC";
String description = "ABCDE";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("191919", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void notifyThis(String title, String message, String var1, String var2, String var3) {
Intent intent = new Intent(this, ChatActivity.class);
intent.putExtra("ChatID",var1);
intent.putExtra("ReceiverID",var2);
intent.putExtra("itemID",var3);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "191919")
.setSmallIcon(R.drawable.ic_launcher_custom_background)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setGroup(GROUP_KEY)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, mBuilder.build());
}
}
Is there any reason? Any chance that it is because of the channelId?
Also, I saw that I might need to build multiple notifications however how can I make it dynamic based on the amount of messages that the user gets?
Lets set I get 2 notifications and then I get one more message but I built only 2 notifications, how it will show me the third?
Thank you
Related
Hi guys as the title suggests I have a problem regarding Firebase Cloud Messaging, everything works perfectly even when the device does not open the app for a long time, receives notifications perfectly, but the problem occurs when I schedule the daily notification via the console firebase li the first time of sending works and sends the notification to all devices, while the next day at the scheduled time the notification is no longer received and this problem I do not know how to solve it, I have tried everything without any solution, the daily notifications do not are received, can you help me thanks.
#SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class MyFirebaseMessagingService extends FirebaseMessagingService {
/*public static int NOTIFICATION_ID = 1;*/
public static String NOTIFICATION = "notification";
public static String NOTIFICATION_CHANNEL_ID = "com.fourapper.forpaper.channel";
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
generateNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
}
private void generateNotification(String body, String title) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
/*PendingIntent pendingIntent = PendingIntent.getActivities(this, 0 , new Intent[]{intent}, PendingIntent.FLAG_ONE_SHOT);*/
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
/*NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);*/
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_logo_forpapaer)
.setVibrate(new long[]{100, 500})
.setSound(soundUri)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("info")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = null;
if (intent.hasExtra(NOTIFICATION)) {
notification = intent.getParcelableExtra(NOTIFICATION);
}
int notificationId = (int) System.currentTimeMillis();
notificationManager.notify(notificationId, notification);
/*if(NOTIFICATION_ID > 2147483646){
NOTIFICATION_ID = 0;
}*/
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("Channel");
notificationChannel.setBypassDnd(true);
notificationChannel.enableLights(true);
notificationChannel.setVibrationPattern(new long[]{ 0, 500});
notificationChannel.enableVibration(true);
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(notificationId, builder.build());
}
}
below the token
public class GettingDeviceTokenService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
String deviceToken = FirebaseInstanceId.getInstance().getToken();
assert deviceToken != null;
Log.d("Device Token", deviceToken);
}
}
Below are the photos of the firebase cloud messaging console for scheduled daily sending at 12:00 AM Recipient Time Zone
sending setting change screen
I get this code from google android developer website, but I'm not sure why I'm getting this error. First I did this in my MainActivity and it works fine, and then I created another at AlarmReceiver.java but error occurred.
error: cannot find symbol method getSystemService(Class)
public class AlarmReceiver extends BroadcastReceiver{
private final String CHANNEL_ID = "Notification";
#Override
public void onReceive(Context context, Intent intent) {
createNotificationChannel();
Intent notificationIntent = new Intent(context, MapsActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MapsActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Demo App Notification")
.setContentText("New Notification From Demo App..")
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, 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 = "NOTIFICATION";
String description = "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);
}
}
}
I want to set notification number on the app icon by button click. I have tried to understand and follow several methods but none of them worked.
I can send notification using simply using channel but I also want to set notification numbers on app icon.
Here below my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Gn = (Button) findViewById(R.id.gn);
Gn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
shownotifications();
}
});
}
private void shownotifications() {
//channel
String id = "main_channel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = "Channel Name";
String description = "Channel Description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(id, name, importance);
notificationChannel.setDescription(description);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.WHITE);
notificationChannel.enableVibration(false);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
//notifications
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, id)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
.setContentTitle("Notification Title")
.setContentText("This is the description of this notification......")
.setLights(Color.WHITE, 500, 5000)
.setColor(Color.RED)
.setDefaults(Notification.DEFAULT_SOUND);
Intent nI = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, nI, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(contentIntent);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(1000, notificationBuilder.build());
}
}
You can only do it by changing your app's icon everytime you want to update the notification number.
Try this.
use this link https://github.com/leolin310148/ShortcutBadger
set count on button click whenever you want to update count user previous count incremented
Notification is showing on android nougat 7.0 and less but not on Orea 8.0
What should i do?
......................................................................................................................................................
Here is my code:
public class MainActivity extends AppCompatActivity {
Button button;
private final String ChannelId = "Notification";
private final Integer NotificationId = 001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
}
public void sendNotification (View view) {
Toast.makeText(this, "Notification", Toast.LENGTH_SHORT).show();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, ChannelId);
Intent i = new Intent(MainActivity.this, Main2Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);
mBuilder.setAutoCancel(true);
mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
mBuilder.setWhen(20000);
mBuilder.setTicker("Ticker");
mBuilder.setContentInfo("Info");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setContentTitle("New notification title");
mBuilder.setContentText("Notification text");
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(2, mBuilder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String channelId = "Notification";
CharSequence channelName = "Some Channel";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
I think you should use notification channel to create the notification
check if Build.VERSION.SDK_INT >= Build.VERSION_CODES.O and then use the channel
here is an example I found on the documentation
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);
}
}
then you use builder to build the notification and then you continue as normal
https://developer.android.com/training/notify-user/channels
This article should be of a good guide to you, according to the new way of implementing Notifications on Android, you need to do that through a Notification Channel
I faced some difficulties implementing this, even though there are so many examples, but here is how it worked for me:
public class RingtonePlayingService extends Service {
NotificationCompat.Builder notificationBuilder;
NotificationManager notificationManager;
NotificationChannel notificationChannel;
String channelId;
CharSequence channelName;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
initNotification();
showNotification();
return START_STICKY;
}
private void initNotification() {
setNotificationChannel();
notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
// The methods called for building are following my own needs, change them according to yours
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.drawable.alarm)
.setContentTitle("Alarm On!")
.setContentText("Click the notification to dismiss")
.setPriority(NotificationCompat.PRIORITY_HIGH)
// You can add your intents or actions here
.setAutoCancel(true);
}
private void showNotification() {
// You can use a unique alarmRequestCode or just use 1 for testing purposes
notificationManager.notify(alarmRequestCode, notificationBuilder.build());
}
private void setNotificationChannel() {
channelId = "alarm_channel_id";
channelName = "alarm_notification_channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
}
}
Please note that I removed the if statement since I upgraded my whole gradle to work only with the new versions.
Also I removed all the snippets of code which you might not need so I can make it easier for you to follow, so if the code doesn't really make sense to you remember that you will need to implement this within your own purpose and code!
I hope this will be of a good help :)
This class won't to handle multiple GCM messages and show them on notification bar,currently handle only one, how can make it to handle multiple messages?
public class GCMIntentService extends GcmListenerService {
private static final String TAG = "GCMIntentService";
int notifyid = 0;
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "from:" + from);
Log.d(TAG, "message:" + message);
sendNotification(message);
}
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notifyid, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("New Messsage")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentIntent(pendingIntent);
int numMessages = 0;
notificationBuilder.setContentText(message).setNumber(++numMessages);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notifyid, notificationBuilder.build());
}
}
}
From the documentation:
public void notify (int id, Notification notification)
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
notifyid never appears to change in the code you've posted, which is why you only see a single notification.