How to set notification number on app icon by button click? - java

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

Related

Why is my code not displaying notifications

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

How to open an activity on the lock screen after FCM notification

How can I open an activity on the lock screen without the user having to click on it? Like for example an alarm or a call.
In my code I can get the FCM notification and if the user clicks on the notification it is possible to open an activity, but I wanted the user not to have to click on it.
FirebaseService.java
//--- Notificacao
public void createNotificationChannel(){
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//create a notification channel
NotificationChannel notificationChannel = new NotificationChannel(PRIMARY_CHANNEL_ID,
"Mascot Notification", NotificationManager
.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Notification from Mascot");
mNotifyManager.createNotificationChannel(notificationChannel);
}
}
public void sendNotification(String taskName){
NotificationCompat.Builder notifyBuilder = getNotificationBuilder(taskName);
//agora temos que entregar a notificacao
mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());
}
public NotificationCompat.Builder getNotificationBuilder(String taskName){
Intent intent = new Intent(this, TesteActivity.class);
PendingIntent p = getPendingIntent(NOTIFICATION_ID, intent, getApplicationContext());
return new NotificationCompat.Builder(this, PRIMARY_CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentText("titulo teste")
.setContentIntent(p)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}
private PendingIntent getPendingIntent(int id, Intent intent, Context context){
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(intent.getComponent());
stackBuilder.addNextIntent(intent);
PendingIntent p = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
return p;
}
TesteActivity.java
public class TesteActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teste);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setTurnScreenOn(true);
setShowWhenLocked(true);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);
}
instead of mNotifyManager.notify( call, which shows your Notification, just use startActivity(..? you may need also WakeLock and showOnLockScreen attribute set for this Activity in manifest
edit: and HERE you can find article with exactly your case tutorial

Group notification wont show

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

Extra null for Android Notification with PendingIntent

I am trying to send a int Extra to an Activity when a notification is tapped. When I tap the notification the activity launches, but the extra is always null.
I have checked a lot of similar questions but they haven't helped me solve the problem. (I tried using onNewIntent() but it was never called). How can I successfully send the Extra?
This is the BroadcastReceiver where the intent is created:
public class EventAlarmNearReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent nextIntent = new Intent().setClass(context, EventActivity.class);
nextIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
int id = 1234;
nextIntent.putExtra("Id", (long) id);
nextIntent.setAction("nearReceiverAction");
PendingIntent nextPendingIntent = PendingIntent.getActivity(context, 1022, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
String text = "Your " + intent.getStringExtra("Name") + " is starting soon. Please read your documents.";
NotificationsDeliver.getInstance().sendNotification(context, "Meeting Mate", text, nextPendingIntent);
}
}
This is the method from NotificationsDeliver where the notification is sent:
public void sendNotification(#NonNull Context context, String title, String text, PendingIntent pendingIntent ) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_event_note_white_24dp)
.setContentTitle(title)
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(new long[] { 1000, 1000, 1000 })
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(999, builder.build());
}
This is onCreate method from EventActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
long id = intent.getLongExtra("id", 0);
}
I would guess that it's because you have capitalized the word "id" differently when putting vs getting the extra; compare:
nextIntent.putExtra("Id", (long) id);
// ^^^^
vs
long id = intent.getLongExtra("id", 0);
// ^^^^
Try using the same capitalization for both.

Notification not working on Oreo

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

Categories