Way to update existing notification? - java

Hi I want notification to behave as follows :
When there is no single notification from my application, then there should be one created, but when there is already a notification in tray, I want to update data of the notification.
Can I get current notification OR any other way of doing this ?
Also I am having a single type of UI + data for notification which gets triggered frequently on occurrence of particular event.
e.g. In situation where application is getting messages about score of a match after every 5 minute, so current notification should be updated based on last message received, there should not be a notification for every score update message.
My code is as follows :
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Constants.SOME_DATA, someData);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

If you want run your single notification permanetly and update that notification than you have to create foreground notification using startForeground(NOTIFICATION_ID, notification);
And than you can update notification by using same NOTIFICATION_ID in which your is case is 0 /* ID of notification */ or if you want simple notification than update your notification with same NOTIFICATION_ID and keeping FLAG_UPDATE_CURRENT in your pending intent

Set flag .setOngoing(true) and always use the same notification id. in this case is 0. it will update your current notification.
Try this demo
public class MainActivity extends Activity {
private ImageView ImageButton;
int value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton = (ImageView) findViewById(R.id.imageButton);
ImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
value++;
UpdateNow(value + "");
}
});
}
void UpdateNow(String msg) {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("asd")
.setContentText(msg)
.setSound(defaultSoundUri)
.setOngoing(true)
.setContentIntent(null);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}

Related

Wrong activity when click a notification (PendingIntent)

I implemented a notification service in my android app (FirebaseMessagingService). When I click a notification, and the app is closed, the wrong activity is opened. If the notification arrives while the app is open (foreground, background), the activity that is opened is correct.
In the following code, the splash activity (first activity of the project) is opened instead of IntroNoti.class.
This is the code of my FireBaseMessagingService class
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
//Log.d(TAG, "From: " + remoteMessage.getFrom());
//Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
Globals.messageIn = true;
sendNotification(remoteMessage);
}
private void sendNotification(RemoteMessage remoteMessage) {
//Intent intent = new Intent(this, Login.class);
Intent intent = new Intent(this, IntroNoti.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_launcher: R.mipmap.ic_launcher;
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setContentText("CIAO CIAO")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Thanks to the advice of #Eugen Pechanec I added this instruction in my MainActivity. The "messageid" property is only valued when the app is opened by the notification.
Thank you all!
if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().size() > 0) {
Log.d(TAG, "Received extras in onCreate()");
Bundle extras = getIntent().getExtras();
if (!extras.getString("messageid","").isEmpty()) {
Globals.fromNotification = true;
}
}
Use PendingIntent.FLAG_UPDATE_CURRENT flag with pending intent . It's work for me.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplication(), CHANNEL_ID)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setContentIntent(getPendingIntent())
.setAutoCancel(true);
private PendingIntent getPendingIntent() {
Intent intent = new Intent(getApplication(), ConversationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
return PendingIntent.getActivity(getApplication(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

How do I get the program to display multiple notifications on the screen?

i cant seem to understand how to display multiple notifications without one overlaying another. In my case it only displays one at the time.
picture 1
My goal is to get it to work like on the screenshot below
picture 2
What should I change or maybe add to my code?
chunk of code assigned for notifications
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("com.example.romanchuk.appisode.notifyId", id);
intent.putExtra("com.example.romanchuk.appisode.show_id", show_id);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, sNotificationId /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(message);
bigText.setBigContentTitle(getString(R.string.app_name));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
Notification notification = null;
notification = builder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(getResources().getColor(R.color.color_accent))
.setContentTitle("Appisode")
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(inboxStyle)
.setSmallIcon(R.drawable.small_icon)
.setSound(defaultSoundUri).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(sNotificationId++, notification);
}
If you want to show multiple notifications, You Notification id should be different, If the notification id already exists in the notifications it will override that notification.
notificationManager.notify(sNotificationId++, notification);
In this sNotificationId should be different for all notification
If your id or show_id is int and not constant and if it will be different for each notification you can use that also as notification id.
Or try to give different tag for each notification like this,
notificationManager.notify(String.valueOf(System.currentTimeMillis()), sNotificationId++, notification);

Pass an object to another activity in notification builder when clicking a notification

Here there is an activity called grouchat. The messages are sent and received by gcmIntent class. In that class I have the code that issues the notification to the mobile.
In our app more than one event is there for groupchat. If I click the notification, it should take me to the right chat window, so I have passed the eventMO by putExtra parcelable. In the groupchat there is code to get a parcelable
The following is the code in groupchat activity:
eventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(eventMO.getEventId());
The following code is in gcmIntend class to build the notification:
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
//here i have messageMO so i just set the eventid from messageMO to eventMO according to get the eventID in groupchat Activity
EventMO eventMO = new EventMO();
eventMO.setEventId(messageMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_dialog_info)
.setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName()))
.setContentText(messageMO.getMessage())
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
Log.e("gcm","eventid"+messageMO.getEventId());
mNotificationManager.notify((int) (long) eventMO.getEventId(), mBuilder.build());
If I clicked the notification it throws a null pointer exception, because I get eventMO as null. Please tell me how to pass the current event id in GcmIntent class to groupchat activity.
I use this code in my projects
Notification
Intent intent = new Intent(context.getApplicationContext(), MainActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(context)//
.setContentTitle(title == null ? context.getString(R.string.app_name) : title)//
.setContentText(message)//
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))//
.setSmallIcon(R.drawable.ic_launcher)//
.setContentIntent(pendingIntent)//
.setTicker(context.getString(R.string.app_name))//
.build();
notification.defaults |= Notification.DEFAULT_ALL;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(id, notification);
In Activity check intent in onCreate and onNewIntent
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
if (getIntent() != null) {
checkIntent(getIntent());
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
checkIntent(intent);
}
private void checkIntent(Intent intent)
{
...
}
You need change getEvent Id to id of notification.
int notification_id = 123;
notificationManager.notify(notification_id, notification);

Clearing Notification from invoked Activity

I use this code to show a notification:
public static void ShowCustomNotification(Context context,String notificationTitle, String notificationMessage)
{
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// intent triggered, you can add other intent for other actions
Intent intent = new Intent(context, ResultActivity.class);
intent.putExtra("title", notificationTitle);
intent.putExtra("body", notificationMessage);
intent.setFlags(PendingIntent.FLAG_UPDATE_CURRENT
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification mNotification = new NotificationCompat.Builder(context)
.setContentTitle(notificationTitle)
.setSmallIcon(R.drawable.office_girl)
.setContentIntent(pIntent)
.setSound(soundUri)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotification);
}
When the user clicks the Notification the activity ResultActivity.class is invoked and everything is fine.
My question is how can i clear the notification on the status bar when a user click on a "Close" button from inside ResultActivity? in case the user click "Back" i dont want to clear the notification.
Thanks.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(YOUR_NOTIFICATION_ID);

How to clear notification on notification action click?

I'm developing an android app where I display notifications with actions. But on action click notification not clearing, It stuck in that shade. How do I clear a notification on action click?
MY CODE
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
PendingIntent openSettingsActivity = PendingIntent.getActivity(this,1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notificationBuilder.addAction(R.drawable.ic_notification_button, "Settings", openSettingsActivity);
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(text);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setColor(color);
notificationBuilder.setSmallIcon(R.drawable.ic_notification);
notificationBuilder.setContentIntent(openSettingsActivity);
final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notificationBuilder.build());
Hiding notifications should be processed in the place where the intent is sent.
In your current code:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
intent.putExtra("hide_notification", true); //add boolean to check later in activity if it should remove notification on activity create
And in your activity smth like this, to check if it should remove notification:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//check for notification remove
boolean hideNotification = getIntent().getBooleanExtra("hide_notification", false);
if (hideNotification) {
NotificationManagerCompat nmc = NotificationManagerCompat.from(this);
nmc.cancel(1); //1 - is your notification id
}
}
Depends on what you want, maybe it will be better to call that not in onCreate() but onStart()

Categories

Resources