Unable to create notifications in android - java

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?

Related

Insistent ongoing notification not working on Android

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.

Notification sent from Service won't show up

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);

Notification not Showing from Service

I searched many other questions related to this topic but found not satisfactory answer also none of them are working for me.
I want to show a continuous notification which should only be terminated by app. But the code i wrote was working a few days ago but not now.
private void GenNotification(String title, String body)
{
try
{
Log.i(Config.TAGWorker, "Generating Notification . . .");
Intent myIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setChannelId("myID")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(false)
.setSmallIcon(R.drawable.floppy)
.setOngoing(true)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notification);
}
catch (Exception e)
{
Log.e(Config.TAGWorker, e.getMessage());
}
}
There is no exception recorded in Logcat, regarding ths. The code is called in onCreate of service. The service is starting correctly i can see in Log cat also there is no exception but notification is not shown. My OS is Android ONE for nokia (PI)
You are using a deprecated NotificationCompat.Builder constructor which takes a single argument (context); and that won't work on starting from Android 8.0 (API level 26).
So, to solve this:
Step 1: Create a Notification channel with the NotificationManager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Notification channels are only available in OREO and higher.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel
("PRIMARY_CHANNEL_ID",
"Service",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Description");
mNotificationManager.createNotificationChannel(notificationChannel);
}
Note: changeargument values as you wish
Step 2:: Use the non-deprecated Notification.Builder class with its two-argument constructor that takes a second argument as the channel ID which you assigned in the first step, where I set it to "PRIMARY_CHANNEL_ID"
Notification notification = new NotificationCompat.Builder
(this, "PRIMARY_CHANNEL_ID")
.setContentTitle("title")
.setContentText("body")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setAutoCancel(true)
.build();
mNotificationManager.notify(0, notification);
Did you check your strings (title and body) is not null if it's null notification wont show
Also check that you call your notification channels when you start your service every time if your android above 7.0
Clear notification when you recall it same id in your case is 1.

Android firebase notification custom ring not working in 8.0 Oreo but default ring is working

i am trying to set custom ring when notification come from firebase, notification is working fine in all devices but when i set custom ringtone it not work in OREO 8 . i already applied many answer from stackoverflow. like "this" but not work for me.
please check the my method code , if write wrong any thing then please read
thanks in advance
void SendNotification(String title,String msg){
Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/raw/message_tone");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,channelId);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(title);
mBuilder.setContentText(msg);
mBuilder.setSound(soundUri);
mBuilder.setAutoCancel(true);
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//If Version OREO Then Get Channel
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel;
String channelId = "channel-01";
String channelName = "Firebase";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
mChannel = new NotificationChannel(channelId, channelName, importance);
mChannel.setSound(soundUri,audioAttributes);
mNotificationManager.createNotificationChannel( mChannel );
mBuilder.setChannelId(channelId);
}
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());
}

User coming from a notification click

I want to trigger a Toast if the user come from a Notification click.
But I don't know how to know if a user is coming from a notification click.
Right know I set the notification like that:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel =
new NotificationChannel(notification_channel, notification_channel, importance);
String description = "A channel which shows notifications about the app";
channel.setDescription(description);
channel.setLightColor(Color.MAGENTA);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().
getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
String notificationTitle = "Title";
String notificationText = "Notification Text";
Intent intent_not = new Intent(getApplicationContext(), Home_Base.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent_not, FLAG_UPDATE_CURRENT);
//build the notification
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(getApplicationContext(), notification_channel)
.setSmallIcon(R.drawable.fiamma)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent);
//trigger the notification
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(123, notificationBuilder.build());
Try setting action (say, On_NOTIFICATION_CLICK) using intent_not.setAction()
In Home_Base using getIntent().getAction(), try to get the action from the intent received.
If the action received in Home_Base is On_NOTIFICATION_CLICK then its a notification Click action.

Categories