Firebase Messaging Service Not Working On Older Android - java

Recently I`ve migrated GCM to FCM and after some struggle, I've managed to make everything work with the help of this great community.
Now when I tested notifications on older version of Android ( Nougat) it doesn't work, app just crash, I've found out that its something related to versions as older ones doesn't support channel managers.
I've found few solutions on StackOverflow but I haven't find a suitable one for my problem so I was hoping someone could toss me a hint or solution.
I appreciate all the answers and help.
public class MessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Message";
public MessagingService() {
super();
}
#TargetApi(Build.VERSION_CODES.O)
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String message = remoteMessage.getData().get("team");
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
String CHANNEL_ID="channel";
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"channel",NotificationManager.IMPORTANCE_HIGH);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
Notification notification=new Notification.Builder(getApplicationContext(),CHANNEL_ID)
.setContentText(message)
// .setContentTitle(title)
.setSound(defaultSound)
.setContentIntent(pendingIntent)
.setChannelId(CHANNEL_ID)
.setSmallIcon(android.R.drawable.sym_action_chat)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.build();
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(1,notification);
}
}

I think it is crashing because Notification Channels dose not supported in android versions older than Oreo.
So you can fix it by adding an android sdk version checker and set notification channel just when app is running on android Oreo or higher:
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(), 1, intent, 0);
Notification notification=new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setContentText(message)
.setSound(defaultSound)
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.sym_action_chat)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.build();
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID="channel";
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"channel",NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(1, notification);
Also notice that I used NotificationCompat.Builder instead of Notification.Builder and removed .setChannel() because it is not necessary when we are passing the channel id in builder constructor.

Related

Notification doesn't work - Android Studio

So I am a beginner and I was following one tutorial on how to make notification in Android Studio. This app should make a notification when you press a button, but instead of making notification it shows up a Developer Warning
Error:
No Channel found for pkg=com.example.myapplication, channelId=My notification, id=1, tag=null, opPkg=com.example.myapplication, callingUid=10153, userId=0, incomingUserId=0, notificationUid=10153, notification=Notification(channel=My notification shortcut=null contentView=null vibrate=null sound=null defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE)
Code(Java):
public void onClick(View v) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this,"My notification");
builder.setContentTitle("My Title");
builder.setContentText("Test");
builder.setSmallIcon(R.drawable.ic_launcher_background);
builder.setAutoCancel(true);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(MainActivity.this);
managerCompat.notify(null,0, builder.build());
}
});
Do you know how to fix this?
Starting with Android 8.0 (API level 26), notifications require a notification channel.
This is a category which you create and assign to your notifications. Having multiple notification channels per app, allows users to better manage which kind of notifications they want to receive from an app.
To achieve this, you need to create a notification channel as stated in the example in the Android docs:
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);
}
}
Source
CHANNEL_ID can be any integer number which doesn't change during the lifetime of your app. It is OK if you make it a static final int.
Once you created the channel, you can specify the same CHANNEL_ID when creating notifications:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(textTitle)
.setContentText(textContent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Source
private Notification getNotification() {
Intent notificationIntent = new Intent(this, VideoExportActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationChannel notificationChannel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel("CHANNEL_ID", "Alarm Time....", NotificationManager.IMPORTANCE_DEFAULT);
}
NotificationManager notificationManager = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
notificationManager = getSystemService(NotificationManager.class);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(notificationChannel);
}
return new NotificationCompat.Builder(this, "CHANNEL_ID")
.setContentTitle("Title")
.setContentText("Your Message")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
}
Notification notification = getNotification();

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 foreground service notification not showing in status bar

I have tried various solution here on SO and can't seem to get any of them to work. The notification simply will not show. Can anyone point out where possible issues in my code could be?
private void startRunningInForeground() {
setupNotificationChannel();
Intent showTaskIntent = new Intent(getApplicationContext(), MainActivity.class);
showTaskIntent.setAction(Intent.ACTION_MAIN);
showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, SERVICE_NOTIFICATION_CHANNEL);
builder.setSmallIcon(R.drawable.ic_stat_ic_logo);
builder.setContentTitle(getString(R.string.merge_notif_title));
builder.setContentText(getString(R.string.merge_notif_description));
builder.setContentIntent(contentIntent);
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(false);
builder.setOngoing(true);
startForeground(NOTIFICATION_ID, builder.build());
}
private void setupNotificationChannel() {
// Only run this on versions of Android that require notification channels.
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return;
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(notificationManager == null) {
return;
}
NotificationChannel cachingChannel = new NotificationChannel(SERVICE_NOTIFICATION_CHANNEL,
getString(R.string.merge_channel), NotificationManager.IMPORTANCE_HIGH);
cachingChannel.setDescription(getString(R.string.merge_channel_description));
cachingChannel.enableLights(false);
cachingChannel.enableVibration(false);
notificationManager.createNotificationChannel(cachingChannel);
}
Not receiving any any error messages and the notification channel is being created because I see it in the app settings.
What does your startForeground do?
try modify this and make sure your os is > Android 8.0
btw the Channel only needs to be created once.
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
NOTIFICATION_ID, <---
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
startForeground(NOTIFICATION_ID, builder.build());
notificationManager.notify(NOTIFICATION_ID, builder.build()); <--
Maybe because of Android O bg service restrictions
//Start service:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this, YourService.class));
} else {
startService(new Intent(this, YourService.class));
}
So I was able to get it to work by extending Service instead of IntentService. I cannot give an explanation as to why this worked, but everything is now working as expected.

Unable to receive local notifications Android

I'm new to Android programming and I'm trying to build my first app. Right now I want to send local notifications. Unfortunately I cannot receive notifications on devices running API 28 and above. I know there is a change in the way notifications are sent since Oreo and I have included code that creates the channel. It seems like if I run the app on a simulator with a lower API (e.g. 19) the notification is received. Also if I copy my code into a new project I receive the notifications, even on a simulator running Android Oreo. What settings in the project could cause notifications not to be received on Android Oreo? (There are no errors in Logcat)
My code for sending the notifications:
public static final String CHANNEL_1_ID = "channel1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannels();
}
public void setNotif(View view) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("hey")
.setContentText("world")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, notification);
}
private void createNotificationChannels() {
// if higher than android oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("This is channel 1");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
}
}
The setNotif method is called by a tap of a button. Again, I'm new to Android programming so any advice would be helpful. Maybe even a different way in which I could diagnose the issue. Thank you!
Add this check in your setNotif() method:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
notificationManager.createNotificationChannel(getNotificationChannel(context));
setNotif() method will be changed like this :
public void setNotif(View view) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("hey")
.setContentText("world")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) notificationManager.createNotificationChannel(getNotificationChannel(context));
notificationManager.notify(1, notification);
}
And getNotificationChannel() method will look like this:
private static NotificationChannel getNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
return null;
CharSequence name = context.getString(R.string.app_name);// The user-visible name of the channel.
int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(BuildConfig.APPLICATION_ID, name, importance);
notificationChannel.setShowBadge(true);
return notificationChannel;
}

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