I have an App which can send notifications to the users but since the new PlayStore Updates needs to match targetSdkVersion 26 the notifications dont work anymore with the error toast Failed to post notification on channel “null”. There are some threads about it but i didnt get the solution. Here is my actual FirebaseMessagingService class:
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#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 from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification_title)
.setContentText(notification_message);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
What do I need to change to make it working again? It would be good if it also works for devices from sdk 24 up.
Since Android Oreo, you need a Channel to send your notifications.
You can do something like this (not tested) :
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
#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 from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification_title)
.setContentText(notification_message);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotifyMgr.createNotificationChannel(notificationChannel);
}
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
Related
So I am trying to create a notification at the top of the phone, but when I run my code it does nothing. Not even a single error. ??? What am I doing wrong here?
public void createNotification(Context ctx) {
SharedPreferences settings = ctx.getApplicationContext().getSharedPreferences(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, 0);
String contactName = settings.getString("curName", String.valueOf(0));
String contactEmail = settings.getString("contactEmail", String.valueOf(0));
String contactNumber = settings.getString("curPhone", String.valueOf(0));
String dueAmount = String.valueOf(settings.getInt("amountDue", 0));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
builder.setSmallIcon(R.drawable.myanlogo);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("LETTING YOU KNOW");
builder.setContentText("Your notification content here.");
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
I have it inside a class like this:
class ContactRVAdapter extends RecyclerView.Adapter<ContactRVAdapter.ViewHolder>
And I am calling the function here:
holder.textDueTomorrow.setVisibility(View.GONE);
if (Integer.valueOf(getFirstDateNumber) == Integer.valueOf(getSecondDateNumber) - 1) {
holder.textDueTomorrow.setVisibility(View.VISIBLE);
createNotification(context);
}
Some advice would be nice because I have been working at this for a while now.
It looks like you're missing Notification Channels for Build.VERSION_CODE.O and greater
https://developer.android.com/develop/ui/views/notifications/channels
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
// Make notification show big text.
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(notificationText);
// Set big text style.
builder.setStyle(bigTextStyle);
} else {
builder.setContentTitle(title);
builder.setContentText(notificationText);
}
This Chanel link below hellped me out along with the example provided below.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
// Make notification show big text.
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(notificationText);
// Set big text style.
builder.setStyle(bigTextStyle);
} else {
builder.setContentTitle(title);
builder.setContentText(notificationText);
}
This link makess it more clear. notification channel is not sending notifications Its basically 100% fine he just forgot to call function createNotificationChannel() before creating the notification.
For Android 8 and higher versions, you need to create a notification channel, write before your notification builder and pass same channel id to NotificationCompat.Builder
Copy/Paste this:
public void createNotification(Context ctx) {
createNotificationChannel();
SharedPreferences settings = ctx.getApplicationContext().getSharedPreferences(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, 0);
String contactName = settings.getString("curName", String.valueOf(0));
String contactEmail = settings.getString("contactEmail", String.valueOf(0));
String contactNumber = settings.getString("curPhone", String.valueOf(0));
String dueAmount = String.valueOf(settings.getInt("amountDue", 0));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, "CHANNEL_ID");
builder.setSmallIcon(R.drawable.myanlogo);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("LETTING YOU KNOW");
builder.setContentText("Your notification content here.");
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
I have update this line NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, "CHANNEL_ID");
JAVA
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("CHANNEL_ID", "Updates", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
KOTLIN
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_DEFAULT
val notificationChannel = NotificationChannel("CHANNEL_ID", "Updates", NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
}
}
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 am using Firebase Push notification to send notification to app. Notification is working in Latest android version's but when i tried to test in Lolipop version .When i test the notification app crashed . I don't know where is the problem. Please help me to solve the issue. Thanks in advance .
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
String title = Objects.requireNonNull(remoteMessage.getNotification()).getTitle();
String message = remoteMessage.getNotification().getBody();
//33
sendNotification(title,message);
}
private void sendNotification(String messageTitle,String messageBody) {
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");
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.sicont)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.sicont))
.setContentTitle(messageTitle)
.setContentText(messageBody)
.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);
assert notificationManager != null;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
assert notificationBuilder != null;
//76 number line
notificationManager.notify(m, notificationBuilder.build());
}
}
Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.Notification androidx.core.app.NotificationCompat$Builder.build()' on a null object reference
at p.MyFirebaseMessagingService.sendNotification(MyFirebaseMessagingService.java:76)
at p.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:33)
at com.google.firebase.messaging.FirebaseMessagingService.zzc(com.google.firebase:firebase-messaging##20.0.0:68)
at com.google.firebase.messaging.zze.run(com.google.firebase:firebase-messaging##20.0.0:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at com.google.android.gms.common.util.concurrent.zza.run(Unknown Source)
Try this method:
private void sendNotification(String messageTitle,String messageBody) {
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");
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.sicont)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.sicont))
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setOnlyAlertOnce(true)
.setChannelId("my_notification")
.setColor(Color.parseColor("#3F5996"));
//.setProgress(100,50,false);
assert notificationManager != null;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m, notificationBuilder.build());
}
After upgrading my app target api to 27 notification is no more working and i get a toast message on android studio emulator:
Failed to post notification on channel “null”
Here is my notification code:
private void sendNotification(Context context, String sysModel) {
Intent intentAction = new Intent(context, MainActivity.class);
intentAction.putExtra("sysModel", sysModel);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intentAction, PendingIntent.FLAG_ONE_SHOT);
notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.changer_ico)
.setContentTitle(context.getString(R.string.service_ready))
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_key_black_24dp, context.getString(R.string.turn_on), pendingIntent)
.setAutoCancel(true);
Notification notification = notificationBuilder.build();
notificationManager.notify(1903, notification);
}
Can you test the code below?
Note that new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL); instead of new NotificationCompat.Builder(context);
private final static String NOTIFICATION_CHANNEL = "channel_name";
private final static String CHANNEL_DESCRIPTION = "channel_description";
public final static int NOTIFICATION_ID = 1903;
private void sendNotification(Context context, String sysModel) {
// Intent
Intent intentAction = new Intent(context, MainActivity.class);
intentAction.putExtra("sysModel", sysModel);
// Pending Intent
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intentAction, PendingIntent.FLAG_ONE_SHOT);
// Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
// Create the notification channel if android >= 8
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, CHANNEL_DESCRIPTION, NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
// Notification builder.. Note that I added the notification channel on this constructor
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL);
notificationBuilder.setSmallIcon(R.drawable.changer_ico)
notificationBuilder.setContentTitle(context.getString(R.string.service_ready))
notificationBuilder.setContentIntent(pendingIntent)
notificationBuilder.addAction(R.drawable.ic_key_black_24dp, context.getString(R.string.turn_on), pendingIntent)
notificationBuilder.setAutoCancel(true);
// Notify
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
In android O you should dispatch notice like follow:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.changer_ico)
.setContentTitle(context.getString(R.string.service_ready))
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_key_black_24dp, context.getString(R.string.turn_on), pendingIntent)
.setAutoCancel(true);
Notification notification = notificationBuilder.build();
NotificationChannel channel = new NotificationChannel("1903",
context.getString(R.string.user_notify), NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
notificationManager.notify(1903, notification);
I created a a function "send_notification" with firebase function and node.js and now at the end it's difficult to figure out how to open a Fragment instead of an Activity in my FirebaseMessagingService class.
this is my code
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo_login)
.setContentTitle(notification_title)
.setContentText(notification_message);
//i need to open a fragment not Main Activiti
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
//----------------------------------------------------
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}