I am using FireBase Cloud Messaging. When I published Message from Console Message coming and Notification Shown. Everything was ok. But, When I used To Come Test Message from the console, It also coming with the help of new token. But, After that When I publish real message (not Test), now the published message not come, only coming the test message. So is there any problem in my codes?
My codes as follows :
public class FirebaseCloudNotification extends FirebaseMessagingService {
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
}
private static final String TAG = "FirebaseMessaging";
private static final String CHANNEL_ID = "com.alquran.tafhimul_quran.FireBaseChannelId";
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if(remoteMessage.getNotification()!=null)
if( remoteMessage.getNotification().getTitle()!=null&& remoteMessage.getNotification().getBody()!=null)
showNotificationCompat(this, _StartActivitySuraList.class,remoteMessage.getNotification().getClickAction() , remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), 555 );
}
public void showNotificationCompat(final Context context, Class<?> cls,String clickAction, String title, String content, final int REQUEST_CODE)
{
Intent intent = new Intent(context, cls);
String t =title+"#"+content;
intent.putExtra("fireBaseNotification", t);
intent.setAction("From.Firebase.Notification");
intent.setData((Uri.parse("####://"+t)));
PendingIntent pendingIntent = PendingIntent.getActivity(context, new Random().nextInt() /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
String channelId = CHANNEL_ID;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.inapp4)
.setContentTitle(title)
.setContentText(content)
.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);
}
notificationManager.notify(3 /* ID of notification */, notificationBuilder.build());
}
From Firebase Cloud Messaging Console I have to remove all test token, (as it is it removed my test device). Then Everything is fine.
For removing all test token you have to click on Test Message (blue ) Button.
Related
I have a problem with notifications where the notification doesn't appear on my xiaomi and samsung devices but works for the other device. I've tried what people recommend like trying auto start, managing battery settings, but it still doesn't appear on both devices. I also tried to use the notify library but the results were the same. Strangely, when I checked the notification setting and then clicked on the application, it appeared as shown below
samsung
This is my notification code :
public void showNotification() {
String appname = "App Name";
String title = "Notification Title";
String text = "This is the notification text";
String iconUrl = "http://url.to.image.com/image.png";
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
TaskStackBuilder stackBuilder = TaskStackBuilder.from(MainActivity.this);
stackBuilder.addParentStack(NewsActivity.class);
stackBuilder.addNextIntent(new Intent(MainActivity.this, NewsActivity.class));
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setContentTitle(title).setContentInfo(appname).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo_wanda_flp)).setContentText(text).setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.logo_wanda_flp);
notifyManager.notify("textid", 123, builder.getNotification());
}
The code won't work on Android 8 (API 26) and above without first registering a notification channel. On Android before that, it will work just fine.
Some of the code snippets below are taken from here.
Creating a notification channel
Register notification channels inside your activity before attempting to show any notification. Alternatively, you can register them inside a custom Application class before any activities or services start (but this won't be shown here for the sake of simplicity).
#Override
public void onCreate(Bundle savedInstanceState) {
createNotificationChannel(); // Registering a notification channel
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
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);
}
}
Deliver the notification
public void showNotification() {
// ...
// NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
// Replace with line below.
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID);
// ...
}
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
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.
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)
I have an Chat app in which a user is subscribed to an topic and each group is a topic. Whenever an message is sent in the group. An notification is sent to that topic.
There are two problems that I am facing.
When the sender sends the message in the group, a notification message is sent to the topic. But before the user gets the notification from firebase, He closes the application or the app goes in the background. So According to the firebase documentations, the notification is sent to the notification tray and not the onMessageReceived callback.
The notification that is received from the firebase is added to the tray. How can the users other than the sender get the notification Id so that i can be cancelled when it required. How can this notification be customised?
Is there a way to keep an active listener for receiving the notification when the app is in the background or terminated.
Please help
You might wan to take a look this.At first I always have problem reading the doc due to english not my primary language. It very confuse but just follow the step you will get more understading.
For your first question you do not need to use both notification and data message. If you use so it will prevent onMessageReceived() get call if the app is in foreground or force close. Trust me just remove the notification{notification:"data"} but keep {data:"something"} while sending to firebase. It will always trigger onMessageReceived().
For you second question after you follow the step above you won't get any notification display on your status bar. Here you can check wether this user is the sender, if it wasn't the sender then you can just show your custom notification inside onMessageReceived().
You can push notification to your app for user engaging with fire base by sending notification,when your app is closed,on basis of some parameters go to fire base .
Make sure Your Project is Added in Fire base first before doing this at all:otherwise add your project in fire base with package name,fingerprint and google_services.json file in app folder of your project .
Fire base Cloud Messaging
it will push notification to your app, if its closed then it let the user to open the app via notification pressed, and if you wants to show notification to the user to direct to another apps of the same account , when the app will be in use both will happened with this code:
Create you first class MyFirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
private static final String ADMIN_CHANNEL_ID ="admin_channel";
private NotificationManager notificationManager;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size()>0){
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(remoteMessage.getData().get("applink")));
PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(this,
0 /* Request code */, notificationIntent,
PendingIntent.FLAG_ONE_SHOT);
int notificationId = new Random().nextInt(60000);
Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("imageurl"));
Intent likeIntent = new Intent(this,LikeService.class);
likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("message"));
PendingIntent likePendingIntent = PendingIntent.getService(this,
notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setLargeIcon(bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getData().get("title"))
.setStyle(new NotificationCompat.BigPictureStyle()
.setSummaryText(remoteMessage.getData().get("message"))
.bigPicture(bitmap))/*Notification with Image*/
.setContentText(remoteMessage.getData().get("message"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.addAction(R.drawable.icon,
getString(R.string.notification_add_to_cart_button),likePendingIntent)
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(){
CharSequence adminChannelName = getString(R.string.notifications_admin_channel_name);
String adminChannelDescription = getString(R.string.notifications_admin_channel_description);
NotificationChannel adminChannel;
adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW);
adminChannel.setDescription(adminChannelDescription);
adminChannel.enableLights(true);
adminChannel.setLightColor(Color.RED);
adminChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(adminChannel);
}
}
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Create another class FirebaseIDService to get instance id service of fire base
public class FirebaseIDService extends FirebaseInstanceIdService {
public static final String FIREBASE_TOKEN = "firebase token";
#Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
preferences.edit().putString(FIREBASE_TOKEN, refreshedToken).apply();
}
Make class Name LikeService
public class LikeService extends Service {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
To Support Notification at Oreo with firebase dont forget to create Channels and this channels initialize in your First Launcher Activity.
in oncreate of your project first launcher activity include these channels;
String channelId = "1";
String channel2 = "2";
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2",NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
Now you have to put your Firebase service class in Mainfest under application tag:
<service android:name=".activities.services.MyFirebaseMessagingService"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
</intent-filter>
</service>
<service android:name=".activities.services.FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Now run your app on your device before push notification with fire base make sure your code is integrated correctly then run app: and go to fire base cloud messaging:
put data as in photo according to your app: when its closed:
if your app is in use then your data written in advance option will show, its data about your promotional app of the same account, don use another account app here,
make sure your key should be like in above class as onMessagede Recieved in MyFirebaseMessagingService class
like
title ,message,applink,imageurl