Android Version 8.1, Bad notification for startForeground - java

I have given my couple of days to solve this issue. My app is getting crash whose android version is 8.1. It is working perfectly fine in Android Version 8.0.
I followed the link mentioned below for the solution and tried many solutions given in this link but my application is not opening.
startForeground fail after upgrade to Android 8.1
I check the Android version in FirebaseMessageService class and create the channel for Oreo version but below given error is showing everytime
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
Here below is my code. Please help me to rectify this problem
public class MyFirebaseMessagingService extends FirebaseMessagingService
{
private NotificationManager notifManager;
Context mContext;
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
sendNotification();
}
public void sendNotification()
{
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, m /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle("Logipace")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
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, "LOGIPACE", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(m /* ID of notification */, notificationBuilder.build());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Below is the code which I used in the onCreate() method of my Activity class.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
// Create channel to show notifications.
String channelId = getString(R.string.default_notification_channel_id);
String channelName = getString(R.string.default_notification_channel_name);
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_LOW));
}
Help me to resolve this issue.

Put your logic inside onMessageReceived: Check Firebase quickstart sample.
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle data payload of FCM messages.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
final String msg = object.getString("msg");
sendNotification(msg);
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.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,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

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.

Turn Screen on when Notification Received

I am building an android application which push notification in specific times and this working well for me and notification received at these times but I want to turn on screen when Notification received.
I searched for that and I found all answers use PowerManager.FULL_WAKE_LOCK which is deprecated now so I need new way for this, How can I do that ?
this is my Notification code
public void ShowNotification(String title, String message, Class acticity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelID, "my app",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = context.getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelID);
builder.setSmallIcon(R.drawable.notif)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.setAutoCancel(true);
Intent intent = new Intent(context, acticity);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.putExtra("clicked", true);
PendingIntent pi = PendingIntent.getActivity(context, 99,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);
Uri sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.sound);
mp = MediaPlayer.create(context, sound);
mp.start();
mcompact.notify(99, builder.build());
}

Unable to create notifications in android

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?

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

Failed to post notification on channel “null” Target Api is 27

After upgrading my app target api to 27 notification is no more working and i get a toast message on android studio emulator:
Failed to post notification on channel “null”
Here is my notification code:
private void sendNotification(Context context, String sysModel) {
Intent intentAction = new Intent(context, MainActivity.class);
intentAction.putExtra("sysModel", sysModel);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intentAction, PendingIntent.FLAG_ONE_SHOT);
notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.changer_ico)
.setContentTitle(context.getString(R.string.service_ready))
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_key_black_24dp, context.getString(R.string.turn_on), pendingIntent)
.setAutoCancel(true);
Notification notification = notificationBuilder.build();
notificationManager.notify(1903, notification);
}
Can you test the code below?
Note that new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL); instead of new NotificationCompat.Builder(context);
private final static String NOTIFICATION_CHANNEL = "channel_name";
private final static String CHANNEL_DESCRIPTION = "channel_description";
public final static int NOTIFICATION_ID = 1903;
private void sendNotification(Context context, String sysModel) {
// Intent
Intent intentAction = new Intent(context, MainActivity.class);
intentAction.putExtra("sysModel", sysModel);
// Pending Intent
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intentAction, PendingIntent.FLAG_ONE_SHOT);
// Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
// Create the notification channel if android >= 8
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, CHANNEL_DESCRIPTION, NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
// Notification builder.. Note that I added the notification channel on this constructor
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL);
notificationBuilder.setSmallIcon(R.drawable.changer_ico)
notificationBuilder.setContentTitle(context.getString(R.string.service_ready))
notificationBuilder.setContentIntent(pendingIntent)
notificationBuilder.addAction(R.drawable.ic_key_black_24dp, context.getString(R.string.turn_on), pendingIntent)
notificationBuilder.setAutoCancel(true);
// Notify
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
In android O you should dispatch notice like follow:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.changer_ico)
.setContentTitle(context.getString(R.string.service_ready))
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_key_black_24dp, context.getString(R.string.turn_on), pendingIntent)
.setAutoCancel(true);
Notification notification = notificationBuilder.build();
NotificationChannel channel = new NotificationChannel("1903",
context.getString(R.string.user_notify), NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
notificationManager.notify(1903, notification);

Categories