Notification is showing on android nougat 7.0 and less but not on Orea 8.0
What should i do?
......................................................................................................................................................
Here is my code:
public class MainActivity extends AppCompatActivity {
Button button;
private final String ChannelId = "Notification";
private final Integer NotificationId = 001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
}
public void sendNotification (View view) {
Toast.makeText(this, "Notification", Toast.LENGTH_SHORT).show();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, ChannelId);
Intent i = new Intent(MainActivity.this, Main2Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);
mBuilder.setAutoCancel(true);
mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
mBuilder.setWhen(20000);
mBuilder.setTicker("Ticker");
mBuilder.setContentInfo("Info");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setContentTitle("New notification title");
mBuilder.setContentText("Notification text");
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(2, mBuilder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String channelId = "Notification";
CharSequence channelName = "Some Channel";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
I think you should use notification channel to create the notification
check if Build.VERSION.SDK_INT >= Build.VERSION_CODES.O and then use the channel
here is an example I found on the documentation
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);
}
}
then you use builder to build the notification and then you continue as normal
https://developer.android.com/training/notify-user/channels
This article should be of a good guide to you, according to the new way of implementing Notifications on Android, you need to do that through a Notification Channel
I faced some difficulties implementing this, even though there are so many examples, but here is how it worked for me:
public class RingtonePlayingService extends Service {
NotificationCompat.Builder notificationBuilder;
NotificationManager notificationManager;
NotificationChannel notificationChannel;
String channelId;
CharSequence channelName;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
initNotification();
showNotification();
return START_STICKY;
}
private void initNotification() {
setNotificationChannel();
notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
// The methods called for building are following my own needs, change them according to yours
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.drawable.alarm)
.setContentTitle("Alarm On!")
.setContentText("Click the notification to dismiss")
.setPriority(NotificationCompat.PRIORITY_HIGH)
// You can add your intents or actions here
.setAutoCancel(true);
}
private void showNotification() {
// You can use a unique alarmRequestCode or just use 1 for testing purposes
notificationManager.notify(alarmRequestCode, notificationBuilder.build());
}
private void setNotificationChannel() {
channelId = "alarm_channel_id";
channelName = "alarm_notification_channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
}
}
Please note that I removed the if statement since I upgraded my whole gradle to work only with the new versions.
Also I removed all the snippets of code which you might not need so I can make it easier for you to follow, so if the code doesn't really make sense to you remember that you will need to implement this within your own purpose and code!
I hope this will be of a good help :)
Related
So I am trying to create a notification at the top of the phone, but when I run my code it does nothing. Not even a single error. ??? What am I doing wrong here?
public void createNotification(Context ctx) {
SharedPreferences settings = ctx.getApplicationContext().getSharedPreferences(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, 0);
String contactName = settings.getString("curName", String.valueOf(0));
String contactEmail = settings.getString("contactEmail", String.valueOf(0));
String contactNumber = settings.getString("curPhone", String.valueOf(0));
String dueAmount = String.valueOf(settings.getInt("amountDue", 0));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
builder.setSmallIcon(R.drawable.myanlogo);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("LETTING YOU KNOW");
builder.setContentText("Your notification content here.");
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
I have it inside a class like this:
class ContactRVAdapter extends RecyclerView.Adapter<ContactRVAdapter.ViewHolder>
And I am calling the function here:
holder.textDueTomorrow.setVisibility(View.GONE);
if (Integer.valueOf(getFirstDateNumber) == Integer.valueOf(getSecondDateNumber) - 1) {
holder.textDueTomorrow.setVisibility(View.VISIBLE);
createNotification(context);
}
Some advice would be nice because I have been working at this for a while now.
It looks like you're missing Notification Channels for Build.VERSION_CODE.O and greater
https://developer.android.com/develop/ui/views/notifications/channels
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
// Make notification show big text.
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(notificationText);
// Set big text style.
builder.setStyle(bigTextStyle);
} else {
builder.setContentTitle(title);
builder.setContentText(notificationText);
}
This Chanel link below hellped me out along with the example provided below.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
// Make notification show big text.
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(notificationText);
// Set big text style.
builder.setStyle(bigTextStyle);
} else {
builder.setContentTitle(title);
builder.setContentText(notificationText);
}
This link makess it more clear. notification channel is not sending notifications Its basically 100% fine he just forgot to call function createNotificationChannel() before creating the notification.
For Android 8 and higher versions, you need to create a notification channel, write before your notification builder and pass same channel id to NotificationCompat.Builder
Copy/Paste this:
public void createNotification(Context ctx) {
createNotificationChannel();
SharedPreferences settings = ctx.getApplicationContext().getSharedPreferences(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, 0);
String contactName = settings.getString("curName", String.valueOf(0));
String contactEmail = settings.getString("contactEmail", String.valueOf(0));
String contactNumber = settings.getString("curPhone", String.valueOf(0));
String dueAmount = String.valueOf(settings.getInt("amountDue", 0));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, "CHANNEL_ID");
builder.setSmallIcon(R.drawable.myanlogo);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("LETTING YOU KNOW");
builder.setContentText("Your notification content here.");
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
I have update this line NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, "CHANNEL_ID");
JAVA
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("CHANNEL_ID", "Updates", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
KOTLIN
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_DEFAULT
val notificationChannel = NotificationChannel("CHANNEL_ID", "Updates", NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
}
}
I replaced this (it allows me to show the notification only when the app was open):
private void addNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel =
new NotificationChannel("MyNotifications", "MyNotifications", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "MyNotifications")
.setContentTitle("Chiamata in arrivo da "+ receiverUserName)
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentText("Apri FtoF per partecipare alla videochiamata");
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(999, builder.build());
}
with this (it allowed me to show the notification even when the app was closed:
public class PushNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//at this point the context has the permission to create remote views
addNotification(context);
setResultCode(Activity.RESULT_OK);
}
private void addNotification(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel =
new NotificationChannel("MyNotifications", "MyNotifications", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "MyNotifications")
.setContentTitle("Chiamata in arrivo")
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentText("Apri FtoF per partecipare alla videochiamata");
NotificationManagerCompat manager = NotificationManagerCompat.from(context);
manager.notify(999, builder.build());
}
}
But now on line 283 this error appears: Cannot resolve method 'addNotification ()'
Does anyone know why?
Complete Code: https://codeshare.io/5D8EgE
lines (111-136) (283)
Thank you
I am using FCM to send notifications between users when they receive a new message.
I had like to make a group notification from my app so it will show like this:
However, for some reason every new notification that I get, it deletes the other so it always shows only the latest notification.
My code is:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private FirebaseAuth auth;
private FirebaseFirestore db;
private static String GROUP_KEY = "NOTIFICATION";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
createNotificationChannel();
notifyThis(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"),remoteMessage.getData().get("var1"),remoteMessage.getData().get("var2"),remoteMessage.getData().get("var3"));
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "ABC";
String description = "ABCDE";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("191919", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void notifyThis(String title, String message, String var1, String var2, String var3) {
Intent intent = new Intent(this, ChatActivity.class);
intent.putExtra("ChatID",var1);
intent.putExtra("ReceiverID",var2);
intent.putExtra("itemID",var3);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "191919")
.setSmallIcon(R.drawable.ic_launcher_custom_background)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setGroup(GROUP_KEY)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, mBuilder.build());
}
}
Is there any reason? Any chance that it is because of the channelId?
Also, I saw that I might need to build multiple notifications however how can I make it dynamic based on the amount of messages that the user gets?
Lets set I get 2 notifications and then I get one more message but I built only 2 notifications, how it will show me the third?
Thank you
I get this code from google android developer website, but I'm not sure why I'm getting this error. First I did this in my MainActivity and it works fine, and then I created another at AlarmReceiver.java but error occurred.
error: cannot find symbol method getSystemService(Class)
public class AlarmReceiver extends BroadcastReceiver{
private final String CHANNEL_ID = "Notification";
#Override
public void onReceive(Context context, Intent intent) {
createNotificationChannel();
Intent notificationIntent = new Intent(context, MapsActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MapsActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Demo App Notification")
.setContentText("New Notification From Demo App..")
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
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 = "NOTIFICATION";
String description = "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);
}
}
}
I want to set notification number on the app icon by button click. I have tried to understand and follow several methods but none of them worked.
I can send notification using simply using channel but I also want to set notification numbers on app icon.
Here below my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Gn = (Button) findViewById(R.id.gn);
Gn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
shownotifications();
}
});
}
private void shownotifications() {
//channel
String id = "main_channel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = "Channel Name";
String description = "Channel Description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(id, name, importance);
notificationChannel.setDescription(description);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.WHITE);
notificationChannel.enableVibration(false);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
//notifications
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, id)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
.setContentTitle("Notification Title")
.setContentText("This is the description of this notification......")
.setLights(Color.WHITE, 500, 5000)
.setColor(Color.RED)
.setDefaults(Notification.DEFAULT_SOUND);
Intent nI = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, nI, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(contentIntent);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(1000, notificationBuilder.build());
}
}
You can only do it by changing your app's icon everytime you want to update the notification number.
Try this.
use this link https://github.com/leolin310148/ShortcutBadger
set count on button click whenever you want to update count user previous count incremented