I want to show notification even if my Android app is running - android

I am using AWS SNS to send push notification to both SNS topics and Device Endpoints. It shows notification if the app is not running but does not show notification while the app is running.
I will like to show notification even if the app is running because the notification will inform the app user of changes happening in another section of the app so they can go check it out when they are ready. Something like getting notification of a new Whatsapp message from another group chat while you are typing message to another person.
Below is the notification builder code. Any hint will be really appreciated. Thanks.
private void displayNotification(final String message) {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
int requestID = (int) System.currentTimeMillis();
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap large_icon = BitmapFactory.decodeResource(this.getResources(),
R.mipmap.myImage);
// Display a notification with an icon, message as content, and default sound. It also
// opens the app when the notification is clicked.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setLargeIcon(large_icon)
.setContentTitle("My Subject Title")
.setContentText(message)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}

I found the problem.
#Override
public void onMessageReceived(final String from, final Bundle data) {
String message = getMessage(data);
Log.d(LOG_TAG, "From: " + from);
Log.d(LOG_TAG, "Message: " + message);
// Display a notification in the notification center if the app is in the background.
// Otherwise, send a local broadcast to the app and let the app handle it.
displayNotification(message);
/* if (isForeground(this)) {
// broadcast notification
broadcast(from, data);
} else {
displayNotification(message);
} */
}
my displayNotification() function was not called because of the "if" conditional statement that will only display notification if the application is not in foreground. So now when onMessageReceived() gets the message it passes it directly to displayNotification() even if my application is currently running, which is what I want.

Use this below code to show notification message.
private static void generateNotification(Context context, final String message)
{
try {
NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent notificationIntent = new Intent(context, DemoActivity.class);
notificationIntent.putExtra("message", message);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, RandomNumberGenerator.getRandom(),notificationIntent
/*new Intent(context, LuncherActivity.class)*/, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.icon_small);
mBuilder.setContentTitle("YOUR-APP-NAME");
// mBuilder.setStyle(new NotificationCompat.BigTextStyle()
// mBuilder.bigText(msg);
mBuilder.setContentText(message);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mBuilder.setSound(soundUri);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Create a random number genetor class like below
public class RandomNumberGenerator {
public static int getRandom()
{
int random_number=0;
Random random = new Random();
random_number= random.nextInt(9999 - 1000) + 1000;
return random_number;
}
}
Try it and let me know.its working in my case.

Related

Sending notification on post added

I am creating a news android app and i want to send a notification when post added to database.i know Google Firebase Console but i want to send notification automatically.i have following codes:
public void sendNotification() {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setPriority(Notification.PRIORITY_MAX);
Intent intent = new Intent(MainActivity.this, NewsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("My Company");
mBuilder.setContentText("New news received.");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(001, mBuilder.build());
}
And using this in Apiservice:
apiService.getNews(new ApiService.OnNewsReceived() {
#Override
public void onReceived(List<News> news) {
sendNotification();
adsesAdapter = new AdsesAdapter(NewsActivity.this, ) );
recyclerView.setAdapter(adsesAdapter);
}
});
This codes just show notification when user is on app... Is there any way to show notification on news received without opening app???

handle different types of notifications in android

I have 3 types of notifications in android.Audio/Video call and msg. How to differentiate based on notification type and open different activity on different notification. THis is hoW I open activity on click of notification.
private void sendNotification(long when,String msg) {
String notificationContent ="Notification Content Click Here to go more details";
String notificationTitle ="This is Notification";
//large icon for notification,normally use App icon
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
int smalIcon =R.drawable.hcp;
String notificationData="This is data : "+msg;
/*create intent for show notification details when user clicks notification*/
Intent intent =new Intent(getApplicationContext(), NotificationDetailsActivity.class);
intent.putExtra("DATA", notificationData);
/*create unique this intent from other intent using setData */
intent.setData(Uri.parse("http://www.google.com"));
/*create new task for each notification with pending intent so we set Intent.FLAG_ACTIVITY_NEW_TASK */
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.hcp)
.setContentTitle("GCM Notification")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(smalIcon)
.setTicker(notificationTitle)
.setLargeIcon(largeIcon)
.setContentText(notificationContent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentIntent(pendingIntent);
;
Notification notification=mBuilder.build();
mBuilder.setContentIntent(pendingIntent);
mNotificationManager.notify((int) when, notification);
Log.d(TAG, "Notification sent successfully.");
}
Assuming that the data (msg) your receiving is from a web service. Now along with the msg parameter, you must be getting some other parameters by which you can distinguish that the following notification is Audio/Video call or message.
So you can create a method that will return the class name which can be used instead of NotificationDetailsActivity.class
private Class<?> getClassFromType(String type) {
if(type.equals("Audio")
return AudioActivity.class;
else if(type.equals("Video")
return VideoActivity.class;
else if(type.equals("Message")
return MessageActivity.class;
}
The final code will be something like this:
Intent intent =new Intent(getApplicationContext(), getClassFromType(type));
Here type will be the variable that distinguishes the notification.
Hope this will solve your problem.

GCM Notification activity is not getting displayed on 2nd Notification upon 1st notificationActivity Display

I implemented Android app in Android device, I also have received the notification from the server.But the problem I am facing is, when the receive activity is open for 1st notification data and when I receive the 2nd Notification, on clicking the notification 2nd, it is not replacing the Receive activity with updated notification data.
Please help me on this
The following code is being used:-
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Context context = getApplicationContext();
//Notification notification = new Notification(icon, message, when); //UM
Log.e(TAG, "Input Extra is...: " + msg);
Intent notificationIntent = new Intent(context, ResultShowActivity.class);
notificationIntent.putExtra("Message",msg);
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
int when= (int) System.currentTimeMillis() ;
//PendingIntent contentIntent = PendingIntent.getActivity(this, iUniqueId,notificationIntent, 0);
PendingIntent contentIntent = PendingIntent.getActivity(this, iUniqueId,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT );
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.gcm_cloud)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setAutoCancel(true)
.setSound(alarmSound)
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
//mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
mNotificationManager.notify(when, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
Welcome to Stack Overflow! To get the best out of this website, you may want to be more specific about your issue. Perhaps add the affected code.
In your case though, it looks like the issue is around your PendingIntent flags. Add FLAG UPDATE CURRENT to update the extras bundle, if that is what you meant to do.

Multiple notification in android for same app not working?

I have implemented push notifications for my android app .I am able to show multiple notification in notification bar but only one notification work at a time.If I click on any notification it will start the intended activity and that particular notification will disappear from notification bar but other notification for same app will become dead.Nothing happens when I click on rest of the notification.My code for handling notification is following:
private void sendNotification(String msg, String msgId, int notificationId,
int type) {
// SharedPreferences prefs = getSharedPreferences(
// Utility.PREFS_NAME, MODE_PRIVATE);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = null;
Bundle bundle = new Bundle();
if (type == 1) {
intent = new Intent(this, Activity_Received.class);
// bundle.putString("greeting", msg);
bundle.putString(Utility.KEY_MESSAGE_DELIVERY_ID, msgId);
} else if (type == 2) {
intent = new Intent(this, Activity_Birth.class);
} else {
return;
}
bundle.putBoolean(Utility.KEY_IS_NOTIFICATION, true);
intent.putExtras(bundle);
PendingIntent contentIntent;
// The stack builder object will contain an artificial back stack
// for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out
// of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
if (type == 1) {
stackBuilder.addParentStack(Activity_Received.class);
} else {
stackBuilder.addParentStack(Activity_Birth.class);
}
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("WishnGreet")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notificationId, mBuilder.build());
}
Please advise what do I need to change in above code so that I can click on every notification that I receive for my application and start the intended activity.
Pass a different notificationId for each different notification you want to have in the method: sendNotification(String msg, String msgId, int notificationId, int type)
I have wrote the following method which is working in case of multiple notifications.
private void pushNotification(String msg, String msgId, int notificationId,
int type) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Bundle bundle = new Bundle();
bundle.putString(Utility.KEY_MESSAGE_DELIVERY_ID, msgId);
bundle.putBoolean(Utility.KEY_IS_NOTIFICATION, true);
Intent intent = new Intent(this, Activity_ReceivedGreeting.class);
intent.putExtras(bundle);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(), notificationId, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("WishnGreet")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notificationId, mBuilder.build());
}
The key was to remove the FLAGS on pending intent.

Android - NotificationCompat.Builder stacking notifications with setGroup(group) not working

I want to stack notifications using setGroup (as described here: https://developer.android.com/training/wearables/notifications/stacks.html)
Basically, I use 0 as notification id (always the same) and builder.setGroup("test_group_key") but a new notification always replaces the previous one.
What could be the problem ?
Code:
public BasicNotifier(Context context) {
super(context);
notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setSound(alarmSound)
.setAutoCancel(true);
stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(getParentActivityClass());
}
public void showNotification(String title, String text, Intent intent, Class cls) {
if (text.length() > 190)
text = text.substring(0, 189) + "...";
mBuilder.setTicker(text).setContentText(text).setContentTitle(title);
Intent notificationIntent = intent == null ? new Intent() : new Intent(intent);
notificationIntent.setClass(getContext(), cls);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setGroup("test_group_key");
Notification notif = mBuilder.build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notifManager.notify(replaceOnNew ? 0 : nextId++, notif); // replaceOnNew
// is "true"
Log.i(TAG, "Notification shown: " + nextId + " = " + title);
}
EDIT:
It seams there is a problem when using NotificationManagerCompat, the notifications are not being displayed at all.
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getContext());
notificationManager.notify(id, notif);
You don't use notification id correctly.
"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."
from Android Developer
So in your case, if you want to stack notification in your group, you need to specify a new id for each new notification.

Categories

Resources