I have been trying to create an incoming call type notification for my Android app, written in native Java code, and in many resources online I have read that using the .setOngoing(true) tag on the NotificationBuilder would be enough to have the desired behaviour of the notification being visible, playing the ringtone sound until it is clicked, but that has not worked for me.
I have also tried using the flags Notification.FLAG_INSISTENT and Notification.FLAG_NO_CLEAR without success.
Here is my current code:
private void ringtone(Context context){
String channelId = "call_channel";
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Incoming Call")
.setContentText("You have an incoming call")
.setCategory(Notification.CATEGORY_CALL)
.setOngoing(true)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(contentIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence channelName = "Incoming Calls";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableVibration(true);
long[] pattern = {0, 1000, 500, 1000};
notificationChannel.setVibrationPattern(pattern);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setLegacyStreamType(AudioManager.STREAM_RING)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
notificationChannel.setAllowBubbles(true);
}
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationChannel.setSound(ringtoneUri,att);
notificationManager.createNotificationChannel(notificationChannel);
}else{
notificationBuilder.setSound(ringtoneUri);
}
Notification notification = notificationBuilder.build();
notification.flags |= Notification.FLAG_INSISTENT | Notification.FLAG_NO_CLEAR;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
My intention is to have an incoming call type of notification much like other applications such as MS Teams, Whatsapp, ETC. and my issue is that the notification gets minimized after showing on screen for a few seconds, and the ringtone stops shortly after. Thank you for any help with this.
Related
I have been trying to get sound and (heads up/pop up) on my notification but nothing is working I read a lot of questions on SO related to this issue and even implement most of them but nothing is working. The only thing which is working with the notification tell yet is its vibration.
Here is my notification channel (in app class)
Im trying to get sound and heads up on channel2
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID_FOR_SERVICE,
utilityClass.NOTIFICATION_CHANNEL_NAME_FIRST, NotificationManager.IMPORTANCE_LOW);
NotificationChannel channel2 = new NotificationChannel(CHANNEL_ID_FOR_REMINDER,
utilityClass.NOTIFICATION_CHANNEL_NAME_SECOND, NotificationManager.IMPORTANCE_HIGH);
channel2.enableVibration(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
channel2.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,audioAttributes);
channel2.setVibrationPattern(new long[]{300, 300, 300});
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
manager.createNotificationChannel(channel2);
}
}
And here I'm creating notification
Intent intent = new Intent(getApplicationContext(), MarkNotificationService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), (int) currentTime, intent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_FOR_REMINDER)
.setSmallIcon(R.drawable.ic_baseline_bookmark_border_24)
.setContentTitle("Title")
.setWhen(System.currentTimeMillis())
.setPriority(NotificationCompat.PRIORITY_MAX)
.addAction(R.drawable.ic_baseline_bookmark_border_24, "Reminder", pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) currentTime, notification);
EDIT: If I manually give floating notification permission in system app sitting then it works fine (heads up)
Add these permissions
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
2.Add build method
public NotificationCompat.Builder createBuilder(Context context
, NotificationManagerCompat manager) {
String channelId = context.getPackageName();
NotificationCompat.Builder notBuilder = new NotificationCompat
.Builder(context, channelId);
notBuilder.setSmallIcon(R.drawable.ic_stat_name);
notBuilder.setColor(Color.parseColor("#3580FF"));
notBuilder.setAutoCancel(true);
notBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND);
notBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notBuilder.setSound(soundUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId
, "Notifications",
NotificationManager.IMPORTANCE_HIGH);
channel.setImportance(NotificationManager.IMPORTANCE_HIGH);
channel.shouldShowLights();
channel.setLightColor(Color.BLUE);
channel.canBypassDnd();
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(soundUri, audioAttributes);
channel.setDescription("Notifications");
notBuilder.setChannelId(channelId);
manager.createNotificationChannel(channel);
}
return notBuilder;
}
3.Show notification
NotificationManagerCompat manager=NotificationManagerCompat.from(context);
NotificationCompat.Builder builder = createBuilder(
context, manager);
builder.setContentTitle(title);
builder.setContentText(message);
builder.setCategory(NotificationCompat.CATEGORY_NAVIGATION);
Intent parentIntent = new Intent(context, ActHome.class);
parentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(context
, NOTIFICATION_ID, parentIntent, PendingIntent.FLAG_ONE_SHOT |
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pIntent);
manager.notify(NOTIFICATION_ID, builder.build());
4.If still doesn't work Uninstall and reinstall the app
I have typed the following function to get notifications in android.
But I get an error which says Failed to post notification on channel "null". I know that I'm missing some piece of code which seems to be inserted for devices running on some newer versions.
Can I get the exact code to be inserted?
void create_notification(String string){
Intent intent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent)
.setContentText(string)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
}
In your builder, you can add the channelID, for example:
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setChannelId("base_channel") //<-- set the name you feel is proper to your project
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent)
.setContentText(string)
.build();
The documentation (first result on google for the search terms "android notification channel") gives the following example:
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);
}
}
And then on your notification you need to specify the channel ID:
Notification notification = new Notification.Builder(this, CHANNEL_ID)
...
Have you tried this?
I'm currently trying to implement a push notification into my app, that will be sent as soon as there's an internet connection. The service for checking the connection works just fine and the showNotifications() Method is being called. But the Notification won't show up in the bar. This is the code:
private void showNotifications(){
Intent intent = new Intent(APITest2.this, Start.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("notif","notify");
PendingIntent contentIntent = PendingIntent.getActivity(APITest2.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder= new NotificationCompat.Builder(APITest2.this)
.setSmallIcon(R.drawable.ic_android)
.setContentTitle("Title")
.setContentText("Text")
.setAutoCancel(true);
builder.setContentIntent(contentIntent);
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,builder.build());
}
Am I missing something?
Thanks in advance for any help!
Use notification manager like below to support all android versions
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("com.package.name");
NotificationChannel channel = new NotificationChannel(
"com.package.name",
"AppName",
NotificationManager.IMPORTANCE_HIGH
);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
notificationManager.notify(0, builder.build());
Create channel as like below,
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
String characterSequence = "Message Alert";
NotificationChannel channel = new NotificationChannel(channelId,
characterSequence,NotificationManager.IMPORTANCE_DEFAULT);
channel.setSound(soundUri,audioAttributes );
NotificationManager manager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
You need to pass channel id here like below,
NotificationCompat.Builder builder= new NotificationCompat.Builder(APITest2.this,channelId)
Also refer https://developer.android.com/training/notify-user/channels
If you need to show heads up notification, then you need to set Importance level in Notification Channel as IMPORTANCE_HIGH. And need to set priority in notification builder as below.
setPriority(NotificationCompat.PRIORITY_HIGH);
I tried almost every fix posted here but this code won't turn on Notification LED at all.
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.defaultChannelId);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this,channelId)
.setLights(Color.RED,200,1000)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setSmallIcon(R.drawable.omega_icon)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.setLightColor(0xFFFFFFFF);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(1, notification);
}
I'm sending notification from Firebase and everything works perfectly fine except the LED lights. LED notification from other apps work fine.
You can't change channel color notification after Oreo/API 26.
developer.android.com
When trying to create a notification within my app, setting a custom notification sound does not work, the system default sound is used. Also, I am trying to enable vibration on my notification, which doesn't work either.
I am trying to set the sound as follows (relevant snippets, see full code below):
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bell);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Order notifications", NotificationManager.IMPORTANCE_MAX);
notificationManager.createNotificationChannel(channel);
channel.setSound(sound,
new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
);
channel.setVibrationPattern(new long[]{0, 500});
} else {
notificationBuilder
.setVibrate(new long[]{0, 500})
.setSound(sound);
}
notificationManager.notify(0, notificationBuilder.build());
My custom sound is a one second long sound snippet, sampled at 44.1 kHz, stored as res/raw/bell.wav. I also tried converting the snippet to different other formats, I tried mp3 and ogg without success.
Regarding the vibration: android.permission.VIBRATE is included in the manifest.
I don't have any more ideas what I am doing wrong. Here is the full code of the sendNotification() function which creates and posts the notification.
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bell);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_web)
.setContentTitle("New order")
.setContentText(messageBody)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Order notifications",
NotificationManager.IMPORTANCE_MAX);
notificationManager.createNotificationChannel(channel);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
channel.setSound(sound, att);
channel.setVibrationPattern(new long[]{0, 500});
} else {
notificationBuilder
.setVibrate(new long[]{0, 500})
.setSound(sound);
}
notificationManager.notify(0, notificationBuilder.build());
}
After you create a NotificationChannel you cannot change things like lights, sound and vibrate. Maybe this is the issue. To see changes you need to first remove the app and install it again.