How to make a heads-up notification on Android? - java

I'm trying to show a notification to the user when a service that runs in the background receives an FCM parcel. The FCM parcel is properly received and parsed, however:
The notification I get on my phone only shows up as a default importance (https://notifee.app/react-native/docs/android/appearance#default) notification.
Here's my code:
// create notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationManager.IMPORTANCE_HIGH);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(new NotificationChannel("default", "default", NotificationManager.IMPORTANCE_HIGH));
NotificationManagerCompat.from(this).notify(0, builder.build());

Related

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?

Notification crashing on emulator and device

I am trying to get a notification to be pushed when a tickbox is checked and a button is clicked to update the record. However when this is clicked, it crashes any emulator and phone devices that is running on a version below 24.
I have got the notification to work on 24 or above which shows the implementation for the notificationcompat builder is correct but it just doesn't seem to work on any device version lower than 24.
Notification Builder:
public void showNotification(String tvSeriesName) {
String notificationText = "You watched '" + tvSeriesName +
"'; how about telling others what you thought of it!";
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Watched TV series")
.setContentText("You've watched:" + tvSeriesName)
.setSmallIcon(R.drawable.ic_tv_24dp)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(notificationText))
.setAutoCancel(true)
.setSubText("")
.setNumber(150)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
mNotificationManager.notify(111, notification);
I am expecting the result to be a notification to pop up displaying You watched tvSeriesName as the title and then how about telling others what you thought but as I say the notification just crashes on any device version lower than 24.
your are using code to execute Notification on api 24 and above using channels , you should use this code for api 23 and below :
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
//if you have custom view
RemoteViews contentView = new RemoteViews(getPackageName(),
mBuilder.setSmallIcon(R.drawable.ic_accessibility_white_36dp);
// if you have custom view
mBuilder.setContent(contentView);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(pendingIntent);
// do not forget to mention the other info , title , text ,.....
// unique id for NOTIFICATION_ID
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

Notification Duration for HeadsUp

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

How to change audio mode programmatically only when notification is happening in android?

I want to ask how to change audio mode temporarily only when notification is happening?
For instance, I want my current mode is silent, no sound and no vibration. When notification is happening sound volume is max and with vibration. After notification is done, I want to change it back to silent mode without sound and vibration.
The problem is, I can change from silent to max volume and with vibration, but the audio settings still max sound with vibration after the notification is done.
This is my code:
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION,
audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION),
AudioManager.FLAG_ALLOW_RINGER_MODES);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(GCMHandler.MESSAGE_NOTIFICATION_ID,
NotificationBuilder.build(context,
"Mohon konfirmasi booking #" + bookings.last().getCode(),
"Booking #"+bookings.last().getCode()+" belum dikonfirmasi!",
NotificationBuilder.Type.PUSH_NOTIFICATION,
R.drawable.notif_icon, 0xFFC200));
and if I put audioManager.setRingerMode(RINGER_MODE_SILENT) after notificationManager.notify(), the notification just built with full silent mode
Regards,
** I think this code will helps to default ringtone in mobile
if you are in silent mode it will vibrate other wise default notification tone
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.piconebg)
.setContentTitle(title)
.setSubText(title3)
.setContentText(message)
.setAutoCancel(true)
.setTicker(title)
.setDefaults(Notification.DEFAULT_LIGHTS)
.setColor(color)
.setStyle(new NotificationCompat.BigTextStyle().bigText(title))
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setWhen(System.currentTimeMillis())
.setLargeIcon(BitmapFactory.decodeResource(PushNotificationService.this.getResources(), R.drawable.push))
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id /* ID of notification unique */,notificationBuilder.build());

Categories

Resources