Android Show Notification only when Message arrives - android

In Android, I have implemented Google Cloud Notification, which notifies when any message arrives, but it stays even when message is there, it shows icon in notification bar immediatly after installing application, is there any way to only show the notification when message arrives and hide it once the user clicks on it ??
Here is my code :
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
//Intent notificationIntent = new Intent(context, MainActivity.class); //Open Activity
// set intent so it does not start a new activity
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse("http://www.google.com")); //Open Link
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}

Without seeing where you are receiving messages and where you want to generate and cancel Notifications, it is very difficult to discern what you need to do to implement this, but I will give it a shot.
If you load the sample project for an Android Connected App Engine project (via GCM), you will notice that GCM data is received in a GCMBaseIntentService.
This class has a method you can override called onMessage() that will be called whenever you receive a GCM message. If you create the notification in this method, then your application will only generate a notification when a GCM message is received.
As for cancelling notifications- you can do so by calling the NotificationManager's cancel() method, passing the ID of the notification you want to cancel. Presumably you have some sort of Activity that displays messages to the user, and this would be a good place to cancel any outstanding Notifications relating to a specific message.

Related

Android: Manage multiple push notification in device of an app

I am developing an application in which i implemented Push notification functionality.
My code of onMessage - GCMIntentService.java is:
#Override
protected void onMessage(Context context, Intent data) {
String message = data.getExtras().getString("message");
displayMessage(context, message);
generateNotification(context, message);
}
And code of generateNotification -
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, GCMMessageView.class);
notificationIntent.putExtra("message", message);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
This code is working fine. I am getting push message and notification.
=>But when i send more then one message the notification gets over write. And i am able to see only last notification in status bar.
The need of application is that - if i send more then one notification then all should be display in status bar.
So please guide me what should i do for that in my code.
Try to put different notification id (i.e. nid) in intent and notify instead of 0 for each new notification this will prevent over writing your notification
PendingIntent intent = PendingIntent.getActivity(context, nid,notificationIntent, 0);
and
notificationManager.notify(nid, notification);
Hope this will help you
Get random numbers:
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
Instead of:
notificationManager.notify(0, notification);
use:
notificationManager.notify(m, notification);
You need to update your Notification ID when you fire a Notification. in
notificationManager.notify(ID, notification);
How?
To set up a notification so it can be different, issue it with a notification ID by calling NotificationManager.notify(ID, notification). To change this notification once you've issued it, create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the Different ID you are not used previously.
If the previous notification is still visible, the system updates it from the contents of the Notification object. If the previous notification has been dismissed, a new notification is created instead.
For more information go to official docs
hello you need to pass unique notification id in notify method.
Below is the code for pass unique notification id:
//"CommonUtilities.getValudeFromOreference" is the method created by me to get value from savedPreferences.
String notificationId = CommonUtilities.getValueFromPreference(context, Global.NOTIFICATION_ID, "0");
int notificationIdinInt = Integer.parseInt(notificationId);
notificationManager.notify(notificationIdinInt, notification);
// will increment notification id for uniqueness
notificationIdinInt = notificationIdinInt + 1;
CommonUtilities.saveValueToPreference(context, Global.NOTIFICATION_ID, notificationIdinInt + "");
//Above "CommonUtilities.saveValueToPreference" is the method created by me to save new value in savePreferences.
Let me know if you need more detail information or any query. :)
notificationManager.notify(Different_id_everytime, notification);

No notification sound through Android device using GCM service

I am delivering notifications through the GCM service to android devices. Delivering messages to client is not a problem its the fact that no sound is played when the notification is received on the phone which is the issue.
I am using the following code on the client side (mono android) to build up notification request
void createNotification(string title, string desc)
{
//Create notification
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
//Create an intent to show ui
var uiIntent = new Intent(this, typeof(Main));
//Create the notification
var notification = new Notification(Android.Resource.Drawable.SymActionEmail, title);
//Auto cancel will remove the notification once the user touches it
notification.Flags = NotificationFlags.AutoCancel;
//Set the notification info
//we use the pending intent, passing our ui intent over which will get called
//when the notification is tapped.
notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0));
//Show the notification
notificationManager.Notify(1, notification);
}
Where in here can I place details of notification sound to play? I have tried the Notification.Sound member but it asks for a uri which I dont have a reference to.
Add this if you want to play custom notification sound
notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
Adding this line of code in function activated default notification sound.
notification.Defaults = NotificationDefaults.Sound;

How to open same activity after clicked difference notifications

i spend a lot of time to resolve my problem. i have written a messenger client in android. my application receive income message and raise a notification. in notification bar i display each income message in a notification item. when click to notification item it will open a conversation activity to list all messages from the beginning until now. everything dose perfect but when i click another item in notification bar, nothing happen! (it must reload data for another conversation). This is my code to raise a notification:
private void showNotification(String message, Class activity, Message messageObject) {
//Get the Notification Service
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence text = message;//getText(R.string.service_started);
Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent callbackIntent = new Intent(context, activity);
if(messageObject != null)
{
callbackIntent.putExtra("conversation", MessageManager.getProvider().getConversation(messageObject.getConversationId()));
}
//callbackIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
int myUniqueValue = new Random().nextInt();
PendingIntent contentIntent = PendingIntent.getActivity(context, myUniqueValue, callbackIntent, PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(context, messageObject.getFrom(), text, contentIntent);
notificationManager.notify(messageObject.getFrom(), myUniqueValue, notification);
}
This is code block to call showNotification function
showNotification(message.getBody(), ConversationActivity.class, messageObject);
Despite your efforts to supply a unique value, those PendingIntents are all treated as the same by the system, so once you click one, the rest are rendered inert.
You'll need to add something distinguishing to callbackIntent; I suggest inventing a data URI that includes the conversation ID or something else that's guaranteed to be different for each notification (see setData).
Finally, I'd encourage you to try to collapse multiple notifications into one icon—you don't want to spam the user. See the Notifications section in the Android Design guide, under "Stack your notifications".
i changed my code and it work very well
private void showNotification(Context context, CharSequence contentTitle, CharSequence contentText, CharSequence notificationContent, Class activity, Conversation conversation) {
//Get the Notification Service
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, notificationContent, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent callbackIntent = new Intent(context, activity);
if(conversation != null)
{
callbackIntent.putExtra("conversation", conversation);
}
callbackIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
int myUniqueValue = new Random().nextInt();
PendingIntent contentIntent = PendingIntent.getActivity(context, myUniqueValue, callbackIntent, PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notificationManager.notify(myUniqueValue, notification);
}

android GCM push notifications

I have successfully set up the code to run GCM over phonegap on an android app. I have managed to secure the handset registration ID and able to send a message to the app using this ID in a PHP script.
My only problem is that the message displays as a javascript alert whilst the app is open, and I am looking to have message sent to the handset's but not showing icon on top notifications bar .
**> does is possible showing icon on top bar in android device
Does anyone know if the GCM plugin for Phonegap is capable of doing this?**
I have using C2DM-Phonegap.
https://github.com/marknutter/GCM-Cordova
please help me friends...
The library you are using specifies what needs to be done when a message is received. You can either modify their code to do what you want or roll your own GCMIntentService.
please refer this links :
https://github.com/phonegap-build/PushPlugin
https://build.phonegap.com/plugins/324
The library you are using specifies what needs to be done when a message is received. You can either modify their code to do what you want or roll your own GCMIntentService.
The quickest way is to add the following code to GCMIntentService.java into the onMessage function. The GCM plugin you are using only receives the GCM message, but you have to trigger notifications on your own. You can also try a cordova plugin for status bar notifications.
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null) {
String message = extras.getString("message");
String title = extras.getString("title");
Notification notif = new Notification(R.drawable.ic_launcher, message, System.currentTimeMillis() );
notif.flags = Notification.FLAG_AUTO_CANCEL;
notif.defaults |= Notification.DEFAULT_SOUND;
notif.defaults |= Notification.DEFAULT_VIBRATE;
Intent notificationIntent = new Intent(context, SomeActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notif.setLatestEventInfo(context, "Title of notification", message, contentIntent);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
mNotificationManager.notify(1, notif);
please check this code
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
// here is your icon drawable instead of ic_launcher
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context.getApplicationContext(), devicephp.class);
// set intent so it does not start a new activity
notificationIntent.putExtra("msg", message);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}

Click on status bar notification and show details?

I wrote an app that saves local notification at specific time in future and when that time is reached it shows notification in status bar even if the app is not running. My question is: it is possible to show some additional information to user when he clicks on notification in status bar?
Yes it is possible to display additional information when user taps on that particular notification. While writing code to display notification, you will find one setLatestEventInfo method. Use it. Its exactly what you need.
public void createNotification(View view) {
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,
"A new notification", System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "This is the title",
"This is the text", activity);
notification.number += 1;
notificationManager.notify(0, notification);
}

Categories

Resources