Not getting Large Icon when app is not in background - android

I am setting large icon for push notification by using following code.
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.green))
.setSound(defaultSoundUri)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo))
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);
This works fine and shows largeIcon when app is in foreground, but when app is not in foreground, it does not display large icon.
I am testing the app in samsung s7(oreo)

The code snipped you posted works fine only when your app is in the foreground because it only gets called when the app is in the foreground. When the application is in the background, the Android system displays the notification for you (based on the 'notification' object in the JSON object that the server sends to the device). Your receiver is not being called at all. Currently, Firebase Cloud Messaging doesn't support setting a large icon as a payload in the request.
A way around this is to not include a 'notification' object in the POST payload of the message. When you only include 'data' object in the payload, your receiver will be asked to handle the notification even when your application is in the background. Then, you can build the notification the same way as if the app was in the foreground and set a large icon for the notification.
Take a look at this answer for a more detailed explanation about this issue.

Try this,
you're recommended to set default values to customize the appearance of notifications. You can specify a custom default icon and a custom default color that are applied whenever equivalent values are not set in the notification payload.
Add these lines inside the application tag to set the custom default icon and custom color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />

Set your application icon transparent
android:icon="#drawable/icon_transper"
and add this lime in AndroidManifest
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/gardi" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
If you set your application icon transparent it can take as notification icon in background.
prefer this link to generate notification icon.
https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=ac_unit&source.space.trim=1&source.space.pad=0&name=ic_stat_ac_unit
I hope this can help you!
Thank You.

It's because you've to set the large icon first and small icon second to that, also you shouldn't use vector images as large icon. Use either Jpeg or PNG images.
new NotificationCompat.Builder(this, channelId)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo))
.setSmallIcon(R.drawable.logo)
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.green))
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);

try once.. Where are you storing your icon in drawable folder .. all the folders like hdpi, xhdpi, xxhdpi.. pls try this once..

You need to check version. If version >= Oreo than you need to add channel id. Please see the sample code below which is working for me:
public void createNotification(Bitmap bitmap, String aMessage, Context context, int icon, String titles, String noti_id, String mid, String att_url, String mname) {
NotificationManager notifManager = null;
final int NOTIFY_ID = 0; // ID of notification
String id = context.getString(R.string.default_notification_channel_id); // default_channel_id
// String title = context.getString(R.string.default_notification_channel_id); // Default Channel
String title = titles;
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
String msg = aMessage;
// bigPictureStyle.setSummaryText("Summary text appears on expanding the notification");
bigPictureStyle.setSummaryText(msg);
bigPictureStyle.bigPicture(bitmap);
if (notifManager == null) {
notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
String m_namse = "Marwadi University - " + mname;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, title, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, FullScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// List<String> test = new ArrayList<String>();
// test.add();
intent.putExtra("title", titles);
intent.putExtra("body", aMessage);
ConstantData.setNotificaitonId(context);
// ConstantData.getNotificaitonId(context);
bundle.putString("values", str);
intent.putExtra("img_path", imageUri);
intent.putExtra("n_id", noti_id);
intent.putExtras(bundle);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.drawable.mu_top_white) // required
.setContentText(m_namse) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(bigPictureStyle)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
} else {
builder = new NotificationCompat.Builder(context, id);
// intent = new Intent(context, AllNotificationActivity.class);
intent = new Intent(context, FullScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("title", titles);
intent.putExtra("body", aMessage);
// intent.putExtra("img_path", imageUri);
intent.putExtra("img_path", imageUri);
intent.putExtra("n_id", noti_id);
intent.putExtra("mid", mid);
ConstantData.setNotificaitonId(context);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.drawable.mu_top_white) // required
.setContentText(m_namse) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(bigPictureStyle)
.setContentIntent(pendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notifManager.notify(NOTIFY_ID, notification);
}
And then Simple call this method:
createNotification(bitmap, message, mContext, R.drawable.main_logo, title, noti_id, mid, att_url, msg);

Related

How Should I Change My Pushnotification Icon For My app

I want to change my push notification icon.
Code Snippet :
public class Mymessagingservice extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage){
super.onMessageReceived(remoteMessage);
getimage(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
public void getimage(String title,String message){
NotificationCompat.Builder builder=new NotificationCompat.Builder(this,"mynotification")
.setContentTitle(title)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
R.drawable.otplogo
))
.setSmallIcon(R.drawable.otplogo)
.setAutoCancel(true)
.setContentText(message);
NotificationManagerCompat manager =NotificationManagerCompat.from(this);
manager.notify(999,builder.build());
}
}
Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.
With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/google_blue" />
Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.
You have to put this tag inside Application tag of manifest
Official doc- https://firebase.google.com/docs/cloud-messaging/android/client
Thanks to this guy - https://stackoverflow.com/a/37332514/4741746
Bro its too simple but you have to do it carefully.
First, make a black & white icon for your notification.
Now set it in your notification as a small icon like below.
mBuilder.setSmallIcon(R.mipmap.notification_icon);
now you can set a color but if I am right so you can set only predefined color instead of custom. For custom color you can try with your logic I am giving you a code of a predefined color.
mBuilder.setColor(Color.GREEN);
It will make your notification icon Color green.
Happy Coding!!!
UPDATE
Code for custom notification.
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
0 /* Request code */, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri soundUri = Uri.parse("android.resource://" + mContext.getApplicationContext()
.getPackageName() + "/" + R.raw.sniper_gun);
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.notification_icon);
mBuilder.setSound(soundUri);
if (image!=null) {
mBuilder.setContentTitle(title)
.setContentText(message)
.setAutoCancel(false)
.setLargeIcon(image)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image).setSummaryText(message).bigLargeIcon(null))
.setColor(Color.GREEN)
.setContentIntent(resultPendingIntent);
}
// else {
// 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});
// set custom soundUri
if(soundUri != null){
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
notificationChannel.setSound(soundUri,audioAttributes);
}
assert mNotificationManager != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());

Notification content text being changed based on different scenarios

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.

Notification image never displays in Android

If suppose I create Notification icons by uploading a png image using Image Asset tool from Android Studio by choosing type as notification would it generate all required icons with the dimensions as needed by notification icon spec? if Yes, then there should not be any problem displaying this icon in the notification bar, isn't it? hmm it doesn't in my case but rather it shows the default App icon no matter what. Below is my code. Any guess why its failing, perhaps this is just a cosmetic issue through.
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("VEDRISE",
"Vedic Notifications",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Will display daily Panchang notificatons");
mNotificationManager.createNotificationChannel(channel);
}
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// URL url = new //URL("https://66.media.tumblr.com/ec76b7d7e0529af6e3a437edb6c6c255/tumblr_phiur//jqePq1xp0noco1_75sq.png");
// Bitmap image = //BitmapFactory.decodeStream(url.openConnection().getInputStream());
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "VEDRISE")
.setSmallIcon(R.drawable.sunrise) // notification icon
// .setLargeIcon(image)
.setContentTitle(title) // title for notification
.setContentText(content)// message for notification
.setSound(alarmSound) // set alarm sound for notification
.setAutoCancel(true); // clear notification after click
Intent intent = new Intent(context, this.getClass());
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
int id = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
Log.d("VedicHoroo", String.format("id: %d", id));
mNotificationManager.notify( id, mBuilder.build());
Just to give you some scope, this requirement is for local notification which will trigger by the AlarmReceiver. The receiver is triggered by Alarm without issues but the Notification does not display image which is set by setSmallIcon instead it display only the App Icon
Notification notification = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pIntent)
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE)
.setAutoCancel(true)
.build();
Even if ic_notification is transparant and white. It must be also defined in the Manifest meta data, like so:
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_notification" />
add this line in the manifest.xml file in application block

On Android 8.1 API 27 notification does not display

I get Toast on Android 8.1 API 27:
Developer warning for package "my_package_name"
Failed to post notification on ...
Logcat includes next strings:
Notification: Use of stream types is deprecated for operations other
than volume control
W/Notification: See the documentation of setSound() for what to use
instead with android.media.AudioAttributes to qualify your playback
use case
E/NotificationService: No Channel found for pkg=my_package_name
The full information in the Toast and in Logcat can help in the localization this problem.
If you get this error should be paid attention to 2 items and them order:
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
builder = new NotificationCompat.Builder(context, id);
Also NotificationManager notifManager and NotificationChannel mChannel are created only once.
There are required setters for Notification:
builder.setContentTitle() // required
.setSmallIcon() // required
.setContentText() // required
See example:
private NotificationManager notifManager;
public void createNotification(String aMessage, Context context) {
final int NOTIFY_ID = 0; // ID of notification
String id = context.getString(R.string.default_notification_channel_id); // default_channel_id
String title = context.getString(R.string.default_notification_channel_title); // Default Channel
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
if (notifManager == null) {
notifManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, title, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(context.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
}
else {
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(context.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notifManager.notify(NOTIFY_ID, notification);
}
Andy's answer is working however I wanted to avoid to deprecated Builder and follow the FireBase Quickstart Project. I just added code before notify from manager.
String channelId = "default_channel_id";
String channelDescription = "Default Channel";
// Since android Oreo notification channel is needed.
//Check if notification channel exists and if not create one
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = notificationManager.getNotificationChannel(channelId);
if (notificationChannel == null) {
int importance = NotificationManager.IMPORTANCE_HIGH; //Set the importance level
notificationChannel = new NotificationChannel(channelId, channelDescription, importance);
notificationChannel.setLightColor(Color.GREEN); //Set if it is necesssary
notificationChannel.enableVibration(true); //Set if it is necesssary
notificationManager.createNotificationChannel(notificationChannel);
}
}
//notificationManager.notify as usual
Edit:
They removed the channel exist check from example I am not sure why.
I have set channel id, but notification still not shown.
Finally i found my problem is had not invoke "setContentText()" method.
It was really help me that #Andy Sander mentioned "required setters"!
here are required setters for Notification on Android 8 Oreo API 26 and later:
builder.setContentTitle() // required
.setSmallIcon() // required
.setContentText() // required
.setChannelId(id) // required for deprecated in API level >= 26 constructor .Builder(this)
Also don't forget to bind your channel_id to your notification builder. After binding it, my problem gone.
notificationBuilder.setChannelId(channelId)
or
NotificationCompat.Builder(Context context, String channelId)

Android O reporting notification not posted to channel - but it is

Couple Android O notification questions:
1) I have created a Notification Channel (see below), am calling the builder with .setChannelId() (passing in the name of the channel I created, "wakey"; and yet, when I run the app, I get a message that I've failed to post a notification to channel "null". What might be causing this?
2) I suspect the answer to #1 can be found in the "log" that it says to check, but I've checked logcat & don't see anything about notifications or channels. Where is the log that it says to look in?
Here's the code I'm using to create the channel:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = context.getString(R.string.app_name);
String description = "yadda yadda"
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
Here's the code to generate the notification:
Notification.Builder notificationBuilder;
Intent notificationIntent = new Intent(context, BulbActivity.class);
notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); // Fix for https://code.google.com/p/android/issues/detail?id=53313
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Intent serviceIntent = new Intent(context, RemoteViewToggleService.class);
serviceIntent.putExtra(WakeyService.KEY_REQUEST_SOURCE, WakeyService.REQUEST_SOURCE_NOTIFICATION);
PendingIntent actionPendingIntent = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
_toggleAction = new Notification.Action(R.drawable.ic_power_settings_new_black_24dp, context.getString(R.string.toggle_wakey), actionPendingIntent);
notificationBuilder= new Notification.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setContentIntent(contentIntent)
.addAction(_toggleAction);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);
}
notificationBuilder.setSmallIcon(icon);
notificationBuilder.setContentText(contentText);
_toggleAction.title = actionText;
int priority = getNotificationPriority(context);
notificationBuilder.setPriority(priority);
notificationBuilder.setOngoing(true);
Notification notification = notificationBuilder.build();
notificationManager.notify(NOTIFICATION_ID, notification);
And here's the warning I'm getting:
I think I have learned a couple things that all add up to an answer:
I was using an emulator device, with an image that did not include the Play Store.
The version of Google Play Services on the image was not the latest, so I should have been getting a notification telling me I needed to upgrade. Since that notification didn't get applied to a channel, it didn't appear.
If I set logcat in Android Studio to "No Filters" instead of "Show only selected application", then I found the logs that pointed out that the notification in question was the Play Services "update needed" notification.
So, I changed to a image with the Play Store included, and it showed the notification properly (maybe the channel for that notification was to be set by the Play Store?), let me update to the latest Google Play Services, and I haven't seen that warning since.
So, long story short (too late) - with Android O, if you are using Google Play Services & testing on the emulator, choose an image with the Play Store included, or ignore the toast (good luck on that one!).
I had the same problem, and resolved it by using the constructor
new Notification.Builder(Context context, String channelId), instead of the one which is deprecated onAPI levels >=26 (Android O) :
new NotificationCompat.Builder(Context context)
The following code won't work if your notificationBuilder is built using the deprecated constructor :
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);}
First create the notification channel:
public static final String NOTIFICATION_CHANNEL_ID = "4565";
//Notification Channel
CharSequence channelName = NOTIFICATION_CHANNEL_NAME;
int importance = NotificationManager.IMPORTANCE_LOW;
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});
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
then use the channel id in the constructor:
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_timers)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setSound(null)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setContent(contentView)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(picture)
.setTicker(sTimer)
.setContentIntent(pendingIntent)
.setAutoCancel(false);
You gotta create a channel before.
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);
}
}
public void notifyThis(String title, String message) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.green_circle)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(0, mBuilder.build());
}
Finally you call this method:
createNotificationChannel();
notifyThis("My notification", "Hello World!");
create a notification using following code :
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannelId(channelId)
.build();
not using :
Notification notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("Some Message")
.setContentText("You've received new messages!")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannel(channelId)
.build();
You have to create a NotificationChannel first
val notificationChannel = NotificationChannel("channelId", "channelName", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(notificationChannel);
This is the only way to show notification for API 26+
I was facing the same problem. It got resolved by creating a NotificationChannel and adding that newly created channel with the notification manager.
I would also like to add that you will receive this error if you're using Build tools v26+:
app/build.grade:
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
targetSdkVersion 26
Downgrading to lowest version should work fine.

Categories

Resources