I am Generating Notification using Firebase ,suppose there are 3 notification if user clicks on any one all the notification are gone ,here what i need is that when user clicks on one notification than the other 2 should be there in notification here is my code wt i have done.
Intent intent;
if (pref.getString("id","").equals("")){
intent = new Intent(this, Login_Activity.class);
}else {
intent = new Intent(this, TicketListActivity.class);
}
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Default";
String msgBody = remoteMessage.getData().get("body");
String ticketid = remoteMessage.getData().get("ticket_Id");
Notification notification = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.app_launch)
.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("body")).setAutoCancel(true).setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getData().get("body")))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setOngoing(true)
.build();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
// manager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);
manager.notify((int) System.currentTimeMillis(), notification);
some info about PendingIntent.FLAG_ONE_SHOT
Flag indicating that this PendingIntent can be used only once. For use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int).
If set, after send() is called on it, it will be automatically canceled for you and any future attempt to send through it will fail.
try to change this flag to FLAG_UPDATE_CURRENT
also avoid this line
(int) System.currentTimeMillis()
currentTimeMillis is long so someday it may throw exception- yes, I know we have a lot of time until this moment, but still... use "real" id as Integer - for PendingIntent you may just put 0, for manager.notify I would advise you to set some int id = 0; and increment it with every posted notification, so every next would have id = prevNotificationId + 1 (use e.g. SharedPreferences for storing last used id)
Related
I write this code to show a notification in android. But this notification is only shown in the status bar. I want when a message received show notifications on the top screen like telegram app:
enter image description here
My code:
NotificationManager mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String offerChannelId = "offerChannelId";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String offerChannelName = "offerChannelName";
String offerChannelDescription = "offerChannelDescription";
int offerChannelImportance = NotificationManager.IMPORTANCE_HIGH;
#SuppressLint("WrongConstant") NotificationChannel notifChannel = new NotificationChannel(offerChannelId, offerChannelName, offerChannelImportance);
notifChannel.setDescription(offerChannelDescription);
mNotifyManager.createNotificationChannel(notifChannel);
}
NotificationCompat.Builder sNotifBuilder = new NotificationCompat.Builder(getBaseContext(), offerChannelId);
sNotifBuilder.setSmallIcon(R.drawable.ic_notifications)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notifications))
.setColor(getResources().getColor(R.color.baseColor_yellow))
.setContentTitle("title")
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_MAX);
mNotifyManager.notify(1, sNotifBuilder.build());
How I do it?
Min SDK is 21.
Thanks in advance.
I found a solution for you. Hope it may help you.
//build notification
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Ping Notification")
.setContentText("Tomorrow will be your birthday.")
.setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
.setPriority(NotificationCompat.PRIORITY_HIGH) //must give priority to High, Max which will considered as heads-up notification
.addAction(R.drawable.dismiss, getString(R.string.dismiss), piDismiss)
.addAction(R.drawable.snooze, getString(R.string.snooze), piSnooze);
//set intents and pending intents to call service on click of "dismiss" action button of notification
Intent dismissIntent = new Intent(this, MyService.class);
dismissIntent.setAction(ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
//set intents and pending intents to call service on click of "snooze" action button of notification
Intent snoozeIntent = new Intent(this, MyService.class);
snoozeIntent.setAction(ACTION_SNOOZE);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
// Gets an instance of the NotificationManager service
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* Notification for oreo*/
String channelId = "channel-01";
String channelName = "Demo";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
//to post your notification to the notification bar with a id. If a notification with same id already exists, it will get replaced with updated information.
notificationManager.notify(0, builder.build());
Minimum SDK is Lolipop.
I am trying to start an activity from a notification. Upon starting that activity, I add data via intent.putextra to the intent so the activity shows the right content for the situation.
The activity that is being started is supposed to be open only once in the stack. I did achieve this via
android:launchMode="singleTop"
in my manifest.
However - and now I come to my question - if this activity is already running, I want it to close and replace it with the instance I am creating with the specific additional data (put extra). How can I achieve this?
Heres the code of my notification:
public void newMessageNotification(String title, String message, String otherusernumber, String requestStatus, String sendername) {
notificationManager = NotificationManagerCompat.from(this);
Intent chatIntent = new Intent(this,ChatActivity.class);
//these three strings define the behaviour of the chat activtity
chatIntent.putExtra("otherUsername", sendername);
chatIntent.putExtra("otherUsernumber", otherusernumber);
chatIntent.putExtra("requestStatus", requestStatus);
chatIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), chatIntent,
PendingIntent.FLAG_UPDATE_CURRENT);;
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_new_message)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(1, notification);
}
Try below code
Add PendingIntent in notification
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Full create notification code
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager =
(NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
Uri defaultSoundUri = RingtoneManager . getDefaultUri (RingtoneManager.TYPE_NOTIFICATION);
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
String Ch_id = "yourappname_01";
// The user-visible name of the channel.
CharSequence name = "Notification";
// The user-visible description of the channel.
//String description = getString(R.string.channel_description);
int importance = NotificationManager . IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(Ch_id, name, importance);
mChannel.setSound(defaultSoundUri, new AudioAttributes . Builder ().build());
notificationManager.createNotificationChannel(mChannel);
// Create a notification and set the notification channel.
notification = new Notification . Builder (this, Ch_id)
.setSmallIcon(R.drawable.notify)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(remoteMessage.getData().get("title"))
.setAutoCancel(true)
.setContentIntent(pendingIntent) //Add PendingIntent
.setChannelId(Ch_id)
.build();
} else {
// Create a notification
notification = new Notification . Builder (this)
.setSmallIcon(R.drawable.notify)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(remoteMessage.getData().get("title"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent) //Add PendingIntent
.build();
}
//Generate Diff Notification
int m =(int)((new Date ().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m, notification);
Update
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_ONE_SHOT);
I hope this can help you!
Thank You.
Try to add flag: Intent.FLAG_ACTIVITY_NEW_TASK to your Intent
Try Below
Intent intent = new Intent(this, ActivityDestination.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//pendingIntent = PendingIntent.getActivity(this, 0,intent,PendingIntent.FLAG_ACTIVITY_NEW_TASK);
I have Implemented heads up notification for my app. Code is like this:
private String CHANNEL_ID = "message_notifications";
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,"message_notifications", NotificationManager.IMPORTANCE_HIGH);
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String user_id = remoteMessage.getData().get("user_id");
String user_name = remoteMessage.getData().get("user_name");
String GROUP_KEY_CHIT_CHAT = "com.android.example.Chit_Chat";
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.chitchat_icon)
.setContentTitle(notification_title)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setGroup(GROUP_KEY_CHIT_CHAT)
.setDefaults(Notification.DEFAULT_ALL)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setContentText(notification_message);
if (Build.VERSION.SDK_INT >= 21) mBuilder.setVibrate(new long[0]);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", user_id);
resultIntent.putExtra("user_name",user_name);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
stackBuilder.addParentStack(MainActivity.class);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel.setShowBadge(true);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mNotificationManager.createNotificationChannel(mChannel);
mBuilder.setChannelId(CHANNEL_ID);
}
mNotificationManager.notify(mNotificationId,mBuilder.build());
}
Problem is It only works correctly when I do the settings for the notification as popup and sound else it appears like simple notification. Whatsapp and other applications are by default settuped to use them. I want to do the same. I want to programmatically set the settings for my app to use heads up notification by default without going into the setting to enable it. Can anybody help me how to do that?
I need to set it to sound and popup it doesn't set by default
Set the importance level of notification channel to IMPORTANCE_HIGH to appears as a heads-up notification.
Set notification as ongoing using setOngoing method if you want the notification dismissed only while performing an action. Ongoing notifications cannot be dismissed by the user, so your application or service must take care of canceling them.
If you want to show the notification in Do Not Disturb mode as well you can set category to CATEGORY_ALARM
If you want an intent to launch instead of posting the notification to the status bar for demanding the user's immediate attention use setFullScreenIntent
Sample code block
Intent launch = new Intent(context, TargetActivity.class);
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
launch, PendingIntent.FLAG_UPDATE_CURRENT);
createNotificationChannel(mContext, NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_HIGH,
R.string.notification_channel_name, R.string.notification_channel_description);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID);
builder.setContentTitle("Title");
builder.setContentText("Content Text");
builder.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Big Content Text"));
builder.setSmallIcon(R.drawable.status_icon);
builder.setFullScreenIntent(pendingIntent, true);
builder.setOngoing(true);
builder.setAutoCancel(true);
builder.setCategory(NotificationCompat.CATEGORY_ALARM);
builder.addAction(0, "Action Text", pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
notificationManager.notify(COMPLETE_NOTIFICATION_ID, builder.build());
/**
* create Notification channel
* #param context
* #param channelId
* #param channelName
* #param channelDescription
*/
#RequiresApi(api = Build.VERSION_CODES.O)
public static void createNotificationChannel(Context context, String channelId, int importance, int channelName, int channelDescription) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getString(channelName);
String description = context.getString(channelDescription);
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
I need to Rewrite all the deprecated methods and class.
private void showNotification(Peer peer, int id) {
CharSequence text = getString(id) + " " + peer.getName();
Notification notification = new Notification(R.drawable.notification, text, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, IPsecToolsActivity.class); //intent.setAction(ACTION_NOTIFICATION);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, getText(R.string.native_service_label), text, contentIntent); //setLatestEventInfo method has been deprecated
// Send the notification.
mNM.notify(peer.getName(), R.string.notify_peer_up, notification);
}
Note that the Notification is deprecated, too old.
Cannot use setLatestEventInfo method.
I need help rewrite it in alternative way.
The way I rewrite this is as following: Please let me know if I was right or not.
private void showNotification(Peer peer, int id) {
CharSequence text = getString(id) + " " + peer.getName();
Context context = this;
Notification notification = new Notification.Builder(context)
.setContentText(text)
.setSmallIcon(R.drawable.notification)
.setWhen(System.currentTimeMillis())
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, IPsecToolsActivity.class);
//intent.setAction(ACTION_NOTIFICATION);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, 0);
// Send the notification.
mNM.notify(peer.getName(), R.string.notify_peer_up, notification);
}
I have a repeating notification in a broadcast receiver. I will like to replace the content text dynamically. The notification will show the user a different message the next time the notification is shown. I want to know if its possible. If yes, how ?
below is the class of my broadcast receiver
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
long pattern[] = {500, 500};
private Uri notifsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
private NotificationCompat.BigTextStyle contentStyle;
#Override
public void onReceive(Context context, Intent intent) {
String msg = "Drivers who sit higher feel as if they're driving slower. " +
"Thus, SUV drivers, who are already piloting the vehicles most prone to " +
"roll, drive faster because they feel like they're creeping along. " +
"So lower your seat to get the sensation of more speed.";
contentStyle = new android.support.v4.app.NotificationCompat.BigTextStyle();
contentStyle.bigText(msg);
contentStyle.setBigContentTitle("Lower Your Seat");
contentStyle.setSummaryText("AutoKit");
NotificationCompat.Builder builder;
builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("AutoKit")
.setContentText("Tip of the Day")
.setTicker("Daily Tip")
.setStyle(contentStyle)
.setSound(notifsound)
.setAutoCancel(true)
.setVibrate(pattern);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, builder.build());
}
}
here is the method is called in my mainactivity and ties the broadcast receiver to an alarm manager
public void setRepeatingAlarm(){ //user receives notifications every 24 hours at 7am
am = (AlarmManager)this.getSystemService(this.ALARM_SERVICE);
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 07);
calendar.set(Calendar.MINUTE, 00);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pi);
}
Modify a Notification
To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(ID, notification). To update this notification once you've issued it, update or create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the same ID you used previously.
The following snippet demonstrates a notification that is updated to reflect the number of events that have occurred. It stacks the notification, showing a summary:
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is
// updated.
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
...
Taken from developer site. please refer, http://developer.android.com/training/notify-user/managing.html
here the changes I made in the broadcast receiver class.
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
long pattern[] = {500, 500};
private Uri notifsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
private NotificationCompat.BigTextStyle contentStyle;
private List contentTexts, contentTitles;
#Override
public void onReceive(Context context, Intent intent) {
contentTexts = new ArrayList<String>();
contentTitles = new ArrayList<String>();
prepareContentTitles();
prepareContentTexts();
SharedPreferences prefs = context.getSharedPreferences("notification_count", context.MODE_PRIVATE);
int count = prefs.getInt("notification_count", 0);
contentStyle = new android.support.v4.app.NotificationCompat.BigTextStyle();
contentStyle.bigText((CharSequence) contentTexts.get(count));
contentStyle.setBigContentTitle((CharSequence) contentTitles.get(count));
contentStyle.setSummaryText("AutoKit");
NotificationCompat.Builder builder;
builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("AutoKit")
.setContentText("Tip of the Day")
.setTicker("Daily Tip")
.setStyle(contentStyle)
.setSound(notifsound)
.setAutoCancel(true)
.setVibrate(pattern);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, builder.build());
if (count == contentTexts.size() - 1) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("notification_count", 0);
editor.commit();
}
else {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("notification_count", count + 1);
editor.commit();
}
}
public void prepareContentTexts() {
contentTexts.add("Drivers who sit higher feel as if they're driving slower. " +
"Thus, SUV drivers, who are already piloting the vehicles most prone to " +
"roll, drive faster because they feel like they're creeping along. " +
"So lower your seat to get the sensation of more speed.");
contentTexts.add("Manufacturers recommend replacing your blades every three months. " +
"Keep a spare set in your trunk. A product such as Rain Clear can also help " +
"minimize the work of your wipers; spray it onto the glass every few weeks. " +
"In some light rains, it makes the wipers almost unnecessary");
contentTexts.add("At the BMW Performance Driving School, instructor Jim Clark says " +
"these four words over and over: \"Slow in, fast out.\" When taking a corner," +
" you need to scrub as much of that speed as you can while the car is braking" +
" in a straight line, then you can accelerate out of the curve. The converse " +
"is \"Fast in, maybe no out.\"");
}
public void prepareContentTitles() {
contentTitles.add("Lower Your Seat");
contentTitles.add("Rainproof Your Windshield");
contentTitles.add("Maneuver Tight Corners ");
}
}
The notification displays different content texts every time it is fired