Cause of Notifications Not Showing up on AndroidDo Not Disturb or Airplane Mode is on. Either system or app notifications are disabled. Power or data settings are preventing apps from retrieving notification alerts. Outdated apps or OS software can cause apps to freeze or crash and not deliver notifications.
Navigate to Settings > Mobile Apps. Click the mobile app for which you'd like to send a push notification. For Device Token, enter the token you located above. For Message, enter a message to display in the push notification.
In Android O it's a must to use a channel with your Notification Builder
below is a sample code :
// Sets an ID for the notification, so it can be updated.
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID)
.build();
Or with Handling compatibility by:
NotificationCompat notification =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setChannelId(CHANNEL_ID).build();
Now make it notify
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
// Issue the notification.
mNotificationManager.notify(notifyID , notification);
or if you want a simple fix then use the following code:
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mNotificationManager.createNotificationChannel(mChannel);
}
Updates: NotificationCompat.Builder reference
NotificationCompat.Builder(Context context)
This constructor was deprecated in API level 26.0.0 so you should use
Builder(Context context, String channelId)
so no need to setChannelId
with the new constructor.
And you should use the latest of AppCompat library currently 26.0.2
compile "com.android.support:appcompat-v7:26.0.+"
Source from Android Developers Channel on Youtube
Also, you could check official Android Docs
Here i post some quick solution function with intent handling
public void showNotification(Context context, String title, String body, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
In addition to this answer, you need to create the notification channel before it can be used.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
/* Create or update. */
NotificationChannel channel = new NotificationChannel("my_channel_01",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
Also you need to use channels only if your targetSdkVersion is 26 or higher.
If you are using NotificationCompat.Builder, you also need to update to the beta version of the support library: https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0-beta2 (to be able to call setChannelId
on the compat builder).
Be careful as this library update raises minSdkLevel to 14.
public class MyFirebaseMessagingServices extends FirebaseMessagingService {
private NotificationChannel mChannel;
private NotificationManager notifManager;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
try {
JSONObject jsonObject = new JSONObject(remoteMessage.getData());
displayCustomNotificationForOrders(jsonObject.getString("title"), jsonObject.getString("description"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void displayCustomNotificationForOrders(String title, String description) {
if (notifManager == null) {
notifManager = (NotificationManager) getSystemService
(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder;
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent;
int importance = NotificationManager.IMPORTANCE_HIGH;
if (mChannel == null) {
mChannel = new NotificationChannel
("0", title, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(this, "0");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
builder.setContentTitle(title)
.setSmallIcon(getNotificationIcon()) // required
.setContentText(description) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource
(getResources(), R.mipmap.logo))
.setBadgeIconType(R.mipmap.logo)
.setContentIntent(pendingIntent)
.setSound(RingtoneManager.getDefaultUri
(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = builder.build();
notifManager.notify(0, notification);
} else {
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = null;
pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(description)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary))
.setSound(defaultSoundUri)
.setSmallIcon(getNotificationIcon())
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(description));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1251, notificationBuilder.build());
}
}
private int getNotificationIcon() {
boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.mipmap.logo : R.mipmap.logo;
}
}
If you can't get the push notification in 26+ SDK version?
your solution is here:
public static void showNotification(Context context, String title, String messageBody) {
boolean isLoggedIn = SessionManager.getInstance().isLoggedIn();
Log.e(TAG, "User logged in state: " + isLoggedIn);
Intent intent = null;
if (isLoggedIn) {
//goto notification screen
intent = new Intent(context, MainActivity.class);
intent.putExtra(Extras.EXTRA_JUMP_TO, DrawerItems.ITEM_NOTIFICATION);
} else {
//goto login screen
intent = new Intent(context, LandingActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
//Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_notification_icon);
String channel_id = createNotificationChannel(context);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)
.setContentTitle(title)
.setContentText(messageBody)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
/*.setLargeIcon(largeIcon)*/
.setSmallIcon(R.drawable.app_logo_color) //needs white icon with transparent BG (For all platforms)
.setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
.setVibrate(new long[]{1000, 1000})
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_HIGH)
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) ((new Date(System.currentTimeMillis()).getTime() / 1000L) % Integer.MAX_VALUE) /* ID of notification */, notificationBuilder.build());
}
public static String createNotificationChannel(Context context) {
// NotificationChannels are required for Notifications on O (API 26) and above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
String channelId = "Channel_id";
// The user-visible name of the channel.
CharSequence channelName = "Application_name";
// The user-visible description of the channel.
String channelDescription = "Application_name Alert";
int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
boolean channelEnableVibrate = true;
// int channelLockscreenVisibility = Notification.;
// Initializes NotificationChannel.
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
notificationChannel.setDescription(channelDescription);
notificationChannel.enableVibration(channelEnableVibrate);
// notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);
// Adds NotificationChannel to system. Attempting to create an existing notification
// channel with its original values performs no operation, so it's safe to perform the
// below sequence.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
return channelId;
} else {
// Returns null for pre-O (26) devices.
return null;
}
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)
-> Here you will get push notification using channel_id
in your device which is consist 26+ SDK version.
-> Because, the NotificationCompat.Builder(context)
is deprecated method now you will use an updated version which is having two parameters one is context, other is channel_id.
-> NotificationCompat.Builder(context, channel_id)
updated method. try it.
-> In 26+ SDK version of device you will create channel_id every time.
Use this class for Android 8 Notification
public class NotificationHelper {
private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public static final String NOTIFICATION_CHANNEL_ID = "10001";
public NotificationHelper(Context context) {
mContext = context;
}
/**
* Create and push the notification
*/
public void createNotification(String title, String message)
{
/**Creates an explicit intent for an Activity in your app**/
Intent resultIntent = new Intent(mContext , SomeOtherActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
0 /* Request code */, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(title)
.setContentText(message)
.setAutoCancel(false)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.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);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert mNotificationManager != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
}
}
First of all, if you dont know, from Android Oreo i.e API level 26 it's compulsory that notifications are resgitered with a channel.
In that case many tutorials might confuse you because they show different example for notification above oreo and below.
So here is is a common code which runs on both above and below oreo:
String CHANNEL_ID = "MESSAGE";
String CHANNEL_NAME = "MESSAGE";
NotificationManagerCompat manager = NotificationManagerCompat.from(MainActivity.this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(MainActivity.this,CHANNEL_ID)
.setSmallIcon(R.drawable.ic_android_black_24dp)
.setContentTitle(TitleTB.getText().toString())
.setContentText(MessageTB.getText().toString())
.build();
manager.notify(getRandomNumber(), notification); // In case you pass a number instead of getRandoNumber() then the new notification will override old one and you wont have more then one notification so to do so u need to pass unique number every time so here is how we can do it by "getRandoNumber()"
private static int getRandomNumber() {
Date dd= new Date();
SimpleDateFormat ft =new SimpleDateFormat ("mmssSS");
String s=ft.format(dd);
return Integer.parseInt(s);
}
Video Tutorial: YOUTUBE VIDEO
In case you want to download this demo: GitHub Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With