No notification sound through Android device using GCM service - android

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;

Related

Get unseen android notifications

I have a service that shows a notification PendingIntent each time it receives a new GCM message. The problem is that the GCM messages can be of different kinds. And if many notifications leave unread, I want not to show them separately but in groups like:
you have 3 unread messages of type A
you have 2 unread messages of type B
you have 4 unread messages of type C
As far as I understand, to get this effect I need to have an access to unread/unseen notifications. Each time when I new notification comes I can check, if there is another unread message of this type, and then decide, whether I create a new notification or update an old one.
My question is: is there a way to see, which notifications are unseen and get access to them?
For any case this is my method to create a message; if an argument notificationId is 0 a new notification should be created. Else - updated.
private int sendNotification(String msg, Integer notificationId) {
Log.d(TAG, "sending message with text: "+msg);
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Random random = new Random();
int notification_id = notificationId==0?random.nextInt(9999 - 1000) + 1000:notificationId;
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.notification);
Intent intent = new Intent(this, MainActivity.class);
// Send data to NotificationView Class
intent.putExtra("text", msg);
PendingIntent pending= PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("escos")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(pending);
mBuilder.setContent(remoteViews);
remoteViews.setTextViewText(R.id.notiftext, msg);
remoteViews.setImageViewResource(R.id.notifim, R.drawable.ic_launcher);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mNotificationManager.notify(notification_id, notification);
return notification_id;
}
For different Notification strip (A, B, C etc.) in your status bar, use different NOTIFICATION_ID for building the Notification on basis of your defined type or collapse_key received from GCM.
For determining unread and read messages, use a local variable (counter) in Shared Preferences and increment it each time a specific type of Notification comes (on basis of defined type or collapse_key).
Then generate the Notification with that particular NOTIFICATION_ID as Notification with particular NOTIFICATION_ID can override each other. So You can override the previous Notification with Iterative Numbered text in New Notification.
As soon as user click on any Notification or particular Notification, clear the notification and reset the value of (counter) in Shared Preferences.
Edit1 : When you click on Notification with particular Pending Intent, then in that Activity use this code for removing all the Notifications generated from your app :
NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
try {
nMgr.cancelAll();
} catch (Exception e) {
e.printStackTrace();
}
Note : Do remember to add Try-Catch before you call cancelAll() as cancelAll() may not be supported by the device model and will generate
java.lang.SecurityException: Permission Denial
error.
Edit 2:
You can also use nMgr.cancel(NOTIFICATION_ID); to clear a specific notification, pass NOTIFICATION_ID to particular intent via extras and get the extras in that activity to cancel a particular notification.
And as you click on any notification it will be cleared from status bar unless you have not set .setAutoCancel(false) in your Notification Builder.

To generate push notification based on user current device location in android

I am able to get push notification from server but my app should receive push notification when user device location change in latitude and longitude.
Case 1:
I have to send device latitude and longitude values to server and it has to send push notification whenever user device current location change.(Moves from Place A to Place B to get notification) even if the app is running in background,app needs to configure with system OS to get push.
Case 2:
Iam able to move to activity while clicking on push notification but i need like if i have received two push notification from server clicking on first notification it has to take FirstActivity and clicking on second push notification take to secondActivity.
How to identify which push notification is to redirect to activity.
code to show push notification in GCMNotificationIntentService:
private void createNotification(String msg){
Log.d(TAG, "Preparing to send notification...: " + msg);
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.offer, "GCM Notification", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, FirstActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, NOTIFICATION_ID,notificationIntent, 0);
notification.setLatestEventInfo(this, "Message From GCM", msg, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_ID, notification);
NOTIFICATION_ID = NOTIFICATION_ID + 1;
}
1.You need to create service which will be runing in background. Also you need somehow send notification to the telephone from your server and handle it. But it could be achived without server, you could just listen to LocationListener.OnLocationChanged
2.According to second question you can prepare right Intent before displaying notification, assign it to the notification, and after clicking it, you will be moved directly to this activity.
Intent intent = //prepare your intent
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentIntent(contentIntent);
notificationManager.notify(notificationId, builder.build());

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

GCM message is getting overridden

I am using GCM push notification to pass some notification to the user. My problem is when am sending single message then this works fine if send more than one then the last message is shown to all the notification.
Where have I made a mistake?
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);
Intent notificationIntent = new Intent(context, GCMMessageView.class);
String[] messageArray = message.split("\\#");
// param :: agentId, Name, Msg
DatabaseHelper db = new DatabaseHelper(context);
int notificationId = db.insertnotifications(messageArray[1], messageArray[0], messageArray[messageArray.length-1]);
notificationIntent.putExtra("message", messageArray[messageArray.length-1]);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentText(messageArray[messageArray.length-1])
.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(icon)
.setWhen(when)
.setContentIntent(intent)
.build();
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(notificationId, notification);
}
used this coding in your notification
int requestID = (int) System.currentTimeMillis();
PendingIntent intent = PendingIntent.getActivity(context, requestID,
notificationIntent,0 );
then your notification will not override i hope this will help u
Make notification id unique for each message. Due to this, it's being overridden.
Yes agree with Dipo's answer. According to Android Notification Developer Guide This is being overridden due to same notification id for more than one notification.SO the last message is being received on receiver end. You need to Implement random unique Notification id for each notifications. There are number of ways to implement this . You can use this
int notificationId = new Random().nextInt();
You can also use system time in Mili Seconds for Notification id.Then you need to pass this unique Notification ID to notificationManager.notify()
Cheers ! Keep Coding
Quite late to answer for the thread but felt it will be helpful for someone. The same implementation works fine for FCM firebase implementation as well
// Get a random value
int notificationId = new Random().nextInt();
// Add the notification ID which is unique as a first value of the notify method.
notificationManager.notify(notificationId, notificationBuilder.build());

Android Show Notification only when Message arrives

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.

Categories

Resources