Notification Duration for HeadsUp - java

Is it possible to set the duration of the headsup notification to unlimited? right now its displayed just for 5 seconds. Already tried different things like changing the category. But the duration always is 5 seconds.
Here is my code:
Notification notification =
notificationBuilder
.setCategory(Notification.CATEGORY_CALL)
.setContentText("TKSE Werk Duisburg")
.setSmallIcon(R.drawable.ic_tk_individual_signet_logo)
.setOngoing(true)
.setAutoCancel(false)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(contentIntent)
.setCustomHeadsUpContentView(viewNotificationHeadsUp) .setCustomContentView(viewNotificationSmall)
.setPriority(Notification.PRIORITY_MAX)
.setVibrate(new long[20]).build();
Tried the same things like on this thread: Controlling Android Notification Duration for HeadsUp but it did not help me.
Interesting fact:
On my Developer Phone a Samsung S5 mini -> its displayed with no time limit
On another Developer Phone a Samsung S7 -> its displayed 5 seconds

This should work. I have added extra onGoing(true) & category call for notification category.
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
// assuming your main activity
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(MainActivity.this, NOTIFICATION_CHANNEL_ID);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setCategory(Notification.CATEGORY_CALL)
.setOngoing(true)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
.setPriority(Notification.PRIORITY_MAX)
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setFullScreenIntent(pendingIntent,true)
.setContentInfo("Info");
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
PS. import android.app.Notification; for setting notification category (call)
Update Android 10
You need to add priority along with category for on going notification.
val fullScreenIntent = Intent(this, CallActivity::class.java)
val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationBuilder =
NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Incoming call")
.setContentText("(919) 555-1234")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
// Use a full-screen intent only for the highest-priority alerts where you
// have an associated activity that you would like to launch after the user
// interacts with the notification. Also, if your app targets Android 10
// or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
// order for the platform to invoke this notification.
.setFullScreenIntent(fullScreenPendingIntent, true)
val incomingCallNotification = notificationBuilder.build()
Source

I have found this page and it has worked
https://developer.android.com/training/notify-user/time-sensitive
val fullScreenIntent = Intent(this, CallActivity::class.java)
val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationBuilder =
NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Incoming call")
.setContentText("(919) 555-1234")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
// Use a full-screen intent only for the highest-priority alerts where you
// have an associated activity that you would like to launch after the user
// interacts with the notification. Also, if your app targets Android 10
// or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
// order for the platform to invoke this notification.
.setFullScreenIntent(fullScreenPendingIntent, true)
and of course use with foregroundService
val incomingCallNotification = notificationBuilder.build()

Try that solution (the one that you have posted as the link..) but after doing that change dont forget to change the NOTIFICATION_ID sometimes if the notification id is not changed some of the previous attributes of the notifications stays .. so
Change the notification id when you change any attribute of notification builder

Related

firebase push notification sound not working on android app in android studio

I have implement Push notification firebase services class and add on my project and send notification API Request through so notification proper receive but notification sound work to app active condition only but it will be require all notification receive time.
any one this type condition face and resolve please suggest changes.
String title = Objects.requireNonNull(remoteMessage.getNotification()).getTitle();
String text = remoteMessage.getNotification().getBody();
remoteMessage.getMessageType();
// String channelId = remoteMessage.getNotification().getChannelId();
// Log.d("channelId", "onMessageReceived: "+channelId);
final String CHANNEL_ID = "HEADS_UP_NOTIFICATION";
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Heads Up notification",
NotificationManager.IMPORTANCE_HIGH
);
getSystemService(NotificationManager.class).createNotificationChannel(channel);
Notification.Builder notification = new Notification.Builder(this,CHANNEL_ID)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.demo)
.setAutoCancel(true)
.setVibrate(new long[] { 0,100,300,500,800,1000, 1000, 1000, 1000, 1000 })
.setOngoing(true)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_SOUND)
.setVisibility(Notification.VISIBILITY_PUBLIC);
// custom notification
/* MediaPlayer mp;
mp = MediaPlayer.create(PushNotificationServices.this, R.raw.short_notification_sound);
mp.start();*/
#SuppressLint("UnspecifiedImmutableFlag") PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
notification.setContentIntent(contentIntent);
NotificationManagerCompat.from(this).notify(1,notification.build());
super.onMessageReceived(remoteMessage);
Try to use setSound method instead of setDefaults.
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notification: Notification.Builder = Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.demo)
.setAutoCancel(true)
.setVibrate(longArrayOf(0, 100, 300, 500, 800, 1000, 1000, 1000, 1000, 1000))
.setOngoing(true)
.setPriority(Notification.PRIORITY_MAX)
--> .setSound(defaultSoundUri)
.setVisibility(Notification.VISIBILITY_PUBLIC)
First You have uninstall your app then try again.
If this does not work for then try using below code
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 = CommonUtill.random();
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody).setBigContentTitle(getString(R.string.app_name)))
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notification);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel mChannel = new NotificationChannel(channelId,
getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription("desc");
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setSound(sound, attributes); // This is IMPORTANT
if (notificationManager != null)
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(943/* ID of notification */, notificationBuilder.build());
This is reference link
Android Push Notification Sound is missing (Not Working ) background and foreground on android

Action icon added in notification not showing up

I am trying to create a notification for Incoming call. For that I have added two actions in notification. My action text only is displayed.Action icon is not displayed in notification.
I want to add icon near Answer and cancel which I added as AddAction in Notification. I have added action icon like below,
NotificationCompat.Action answerAction = new NotificationCompat.Action.Builder(R.drawable.answer_call_icon, "Answer", pendingIntent).build();
NotificationCompat.Action cancelAction = new NotificationCompat.Action.Builder(R.drawable.cancel, "Cancel", pendingIntent).build();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setLargeIcon((BitmapFactory.decodeResource(getResources(), R.drawable.call_logo)))
.setContentTitle(intent.getStringExtra("Number"))
.setSmallIcon(R.drawable.call_logo)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setFullScreenIntent(pendingIntent, true)
.setCategory(NotificationCompat.CATEGORY_CALL)
.addAction(answerAction)
.addAction(cancelAction)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat nManager = NotificationManagerCompat.from(this);
nManager.notify(2,builder.build());
One more query,
Below is my notification channnel,
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.FLAG_FOREGROUND_SERVICE);
chan.setImportance(NotificationManager.IMPORTANCE_HIGH);
chan.setSound(defaultRingToneUri,audioAttributes);
chan.enableLights(true);
chan.shouldShowLights();
chan.setVibrationPattern(vibrate);
chan.enableVibration(true);
Context context=getApplicationContext();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
Not able to get ringtone while receiving notification. Is the way Im setting sound is right??
Anybody please help me to solve this...
Posted 2 days ago..but till now not able to find solution.
As per the Notifications in Android N blog post:
Notification actions have also received a redesign and are now in a visually separate bar below the notification.
You’ll note that the icons are not present in the new notifications; instead more room is provided for the labels themselves in the constrained space of the notification shade. However, the notification action icons are still required and continue to be used on older versions of Android and on devices such as Android Wear.
So it is expected that you do not see the icons associated with notification actions.
If you need more flexibility in creating the notification layout, go for the custom one.
Ref: https://developer.android.com/training/notify-user/custom-notification
Use the Drawable left/right option to set an icon with text in the button.
// Get the layouts to use in the custom notification
RemoteViews notificationLayout = new RemoteViews(getPackageName(), R.layout.notification_small);
RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.notification_large);
// Apply the layouts to the notification
Notification customNotification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.build();
As I understand: you have a problem with your notification you can use this method :
private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Constant.NOTIFICATION_ID, notification);
}
or this one :
private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
bigPictureStyle.bigPicture(bitmap);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(bigPictureStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Constant.NOTIFICATION_ID_BIG_IMAGE, notification);
}
To play ringtone you can make use of android mediaplayer as shown below:
Var _mediaPlayer = MediaPlayer.Create(this,
Android.Provider.Settings.System.DefaultRingtoneUri);
_mediaPlayer.Start();
Task.Delay(60 * 1000).ContinueWith(t => _mediaPlayer?.Stop()); //stop after 60sec
You can take the global instance of _mediaPlayer and stop this as per user interaction with notification.
This is the c# xamarin android example, you can use the same class with java syntax.

Android NotificationManager not alerting user

I have the same issue as this person: NotificationManager Error Android Studio
However I already have the solution implemented a while ago but this just stopped working. I am at build API 28 on a P10 with Oreo 8.0.0 installed. My code executes the notification logic, but I get this error:
E/NotificationManager: notifyAsUser: tag=null, id=-1522221101, user=UserHandle{0}
and even though the icon for the notification pops up in the phone's notification bar, and tapping it opens my intent, the user gets no notification that this message arrived. I tried with the app in the foreground and in the background - both cases the small icon appears in the notification bar on top of the phone's UI, but no sound and no message.
Here is my code:
Intent intent = new Intent(getContext(), AuthRequestActivity.class);
intent.putExtra(getContext().getPackageName().concat(".param0"), code);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("default", "My Channel", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("ALP Push Notifications");
notificationManager.createNotificationChannel(channel);
}
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "default").setSmallIcon(R.drawable.app_icon)
.setContentTitle("Authentication Request").setContentText(code)
.setAutoCancel(true).setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getContext());
// Below alternative makes no difference
// NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) System.currentTimeMillis(), notificationBuilder.build());
What am I doing wrong?

Android: Notification that requires user interaction / input

I'm programming some Android App that must make some Notification/Alarm after event occurs. Im wondering is there any function for NotificationManager like requireInteraction()?
Now when the certain event occurs the app just shows one notification for 1 sec, that's it..i'd like user to click OK to stop this vibration/sound
I found some code for notification from here:
NotificationCompat.Builder deprecated in Android O
Thanks #Mehul
public void showNotification (String from, String notification,
Intent intent) {
int requestID = (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
requestID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification mNotification = builder
.setContentTitle(from)
.setContentText(notification)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.build();
notificationManager.notify(/*notification id*/requestID, mNotification);
}
This one shows notification and it doesnt wait for user Input
If there is a need to add the buttons or action after clicking on notification you can use in your builder:
To add an button:
.addAction(new NotificationCompat.Action(*icon*, "Title", *intent for notification*));
or to add action that happen after user click the notification
.setContentIntent(*intent*);
Check the documentation about tab action and actions if you need more details.

Why it Showing deprecated API usage in Notificationcompat.Builder [duplicate]

After upgrading my project to Android O
buildToolsVersion "26.0.1"
Lint in Android Studio is showing a deprecated warning for the follow notification builder method:
new NotificationCompat.Builder(context)
The problem is: Android Developers update their Documentation describing NotificationChannel to support notifications in Android O, and provide us with a snippet, yet with the same deprecated warning:
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();
Notifications Overview
My question: Is there is any other solution for building notification, and still support Android O?
A solution I found is to pass the channel ID as a parameter in Notification.Builder constructor. But this solution is not exactly reusable.
new Notification.Builder(MainActivity.this, "channel_id")
It is mentioned in the documentation that the builder method NotificationCompat.Builder(Context context) has been deprecated. And we have to use the constructor which has the channelId parameter:
NotificationCompat.Builder(Context context, String channelId)
NotificationCompat.Builder Documentation:
This constructor was deprecated in API level 26.0.0-beta1. use
NotificationCompat.Builder(Context, String) instead. All posted
Notifications must specify a NotificationChannel Id.
Notification.Builder Documentation:
This constructor was deprecated in API level 26. use
Notification.Builder(Context, String) instead. All posted
Notifications must specify a NotificationChannel Id.
If you want to reuse the builder setters, you can create the builder with the channelId, and pass that builder to a helper method and set your preferred settings in that method.
Here is working code for all android versions as of API LEVEL 26+ with backward compatibility.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
UPDATE for API 26 to set Max priority
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
// .setPriority(Notification.PRIORITY_MAX)
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
Call the 2-arg constructor: For compatibility with Android O, call support-v4 NotificationCompat.Builder(Context context, String channelId). When running on Android N or earlier, the channelId will be ignored. When running on Android O, also create a NotificationChannel with the same channelId.
Out of date sample code: The sample code on several JavaDoc pages such as Notification.Builder calling new Notification.Builder(mContext) is out of date.
Deprecated constructors: Notification.Builder(Context context) and v4 NotificationCompat.Builder(Context context) are deprecated in favor of Notification[Compat].Builder(Context context, String channelId). (See Notification.Builder(android.content.Context) and v4 NotificationCompat.Builder(Context context).)
Deprecated class: The entire class v7 NotificationCompat.Builder is deprecated. (See v7 NotificationCompat.Builder.) Previously, v7 NotificationCompat.Builder was needed to support NotificationCompat.MediaStyle. In Android O, there's a v4 NotificationCompat.MediaStyle in the media-compat library's android.support.v4.media package. Use that one if you need MediaStyle.
API 14+: In Support Library from 26.0.0 and higher, the support-v4 and support-v7 packages both support a minimum API level of 14. The v# names are historical.
See Recent Support Library Revisions.
Instead of checking for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O as many answers suggest, there is a slightly simpler way -
Add the following line to the application section of AndroidManifest.xml file as explained in the Set Up a Firebase Cloud Messaging Client App on Android doc:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id" />
Then add a line with a channel name to the values/strings.xml file:
<string name="default_notification_channel_id">default</string>
After that you will be able to use the new version of NotificationCompat.Builder constructor with 2 parameters (since the old constructor with 1 parameter has been deprecated in Android Oreo):
private void sendNotification(String title, String body) {
Intent i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this,
0 /* Request code */,
i,
PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
getString(R.string.default_notification_channel_id))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(sound)
.setContentIntent(pi);
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
Here is the sample code, which is working in Android Oreo and less than Oreo.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
notificationManager.createNotificationChannel(notificationChannel);
builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
} else {
builder = new NotificationCompat.Builder(getApplicationContext());
}
builder = builder
.setSmallIcon(R.drawable.ic_notification_icon)
.setColor(ContextCompat.getColor(context, R.color.color))
.setContentTitle(context.getString(R.string.getTitel))
.setTicker(context.getString(R.string.text))
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
notificationManager.notify(requestCode, builder.build());
Simple Sample
public void showNotification (String from, String notification, Intent intent) {
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
Notification_ID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification mNotification = builder
.setContentTitle(from)
.setContentText(notification)
// .setTicker("Hearty365")
// .setContentInfo("Info")
// .setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
// .setDefaults(Notification.DEFAULT_ALL)
// .setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.build();
notificationManager.notify(/*notification id*/Notification_ID, mNotification);
}
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();
Right code will be :
Notification.Builder notification=new Notification.Builder(this)
with dependency 26.0.1 and new updated dependencies such as 28.0.0.
Some users use this code in the form of this :
Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.
So Logic is that which Method you will declare or initilize then the same methode on Right side will be use for Allocation. if in Leftside of = you will use some method then the same method will be use in right side of = for Allocation with new.
Try this code...It will sure work
Need to declare a Notification channel with Notification_Channel_ID
Build notification with that channel ID.
For example,
...
public static final String NOTIFICATION_CHANNEL_ID = MyLocationService.class.getSimpleName();
...
...
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_ID+"_name",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.notification_text))
.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.ic_tracker)
.setPriority(PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_SERVICE);
startForeground(1, builder.build());
...
This constructor was deprecated in API level 26.1.0.
use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.
I build this code which allows you show notificaciones to android api level < 26 or api level >= 26
private void showNotifcation(String title, String body) {
//Este método muestra notificaciones compatibles con Android Api Level < 26 o >=26
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Mostrar notificacion en Android Api level >=26
final String CHANNEL_ID = "HEADS_UP_NOTIFICATIONS";
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"MyNotification",
NotificationManager.IMPORTANCE_HIGH);
getSystemService(NotificationManager.class).createNotificationChannel(channel);
Notification.Builder notification = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true);
NotificationManagerCompat.from(this).notify(1, notification.build());
}else{
//Mostrar notificación para Android Api Level Menor a 26
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
}
}
Cheers!

Categories

Resources