Android: Push Notification has no Sound/Vibration/Light - android

I'm not getting sound, vibration or light when receiving a notification. Can someone please tell me what I'm missing?
Also I have some other questions:
1.) I only get the specified icon when the app is open. When the app is closed I get the android logo icon (I guess thats because I havent defined an app icon yet).
2.) The ticker text is only shown when the app is open.
3.) When the app is open I dont get the content text, only the content title.
SOLUTION: This happens because I am using com.google.android.gms:play-services-gcm:8.4.0 over the previous version.
Make sure that on the server you send a notification array containing only the key/value pair e=0 while sending your message information in the data array.
This problem has already a great answer here: After updating Google play services to 8.4.0 push notifications displayed by themselves
This is my Source:
public class MyGcmListenerService extends GcmListenerService {
private final static String TAG = "GCM_Listener";
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from + " (" + message);
// Sets an ID for the notification
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.sharedPreferenceStore_default), Context.MODE_PRIVATE);
int mNotificationId = sharedPreferences.getInt("id_notification", 0);
mNotificationId++;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.all_picks_made_indicator)
.setAutoCancel(true)
.setContentTitle("Product - " + mNotificationId)
.setContentText(message)
.setTicker("Product Notification received");
// Because clicking the notification opens a new ("special") activity, there's no need to create an artificial back stack.
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, DetectLoginActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
Notification notification = mBuilder.build();
notification.defaults = Notification.DEFAULT_ALL;
mNotifyMgr.notify(mNotificationId, notification);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("id_notification", mNotificationId);
editor.commit();
}
}

Custom Sound for Push Notification
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pop);
In your code change
Notification notification = mBuilder.build();
notification.defaults = Notification.DEFAULT_ALL;
mNotifyMgr.notify(mNotificationId, notification);
To.
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" +R.raw.pop);
notification.defaults |= Notification.DEFAULT_VIBRATE;

mBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
mBuilder.setLights(getResources().getColor(R.color.mainColor), 1000, 1000);
you can set color and vibrate on the builder object

You're missing something like this:
long[] pattern = new long[]{0, 100, 200, 100}; //two short beeps
mBuilder.setVibrate(pattern);
Notification note = mBuilder.build();
note.vibrate = pattern;
That will give you vibrations. Look into lights, I don't have that code at hand atm.

Related

How to use different sounds on one notification channel for an Android Foreground Service

I have a foreground service that I set up a notification channel as required for Android API 26 and beyond, but I'm not able to dynamically set the sound for this notification. Let me explain:
As the service starts, it creates an initial notification using startForeground as required of a foreground service. What I'm trying to accomplish is to reuse this persistent notification that is already in the notification tray, updating the message to provide a visual status update. This much I can already achieve. In one particular case, I'd like to also update either the notification or notification channel to provide a new notification sound and display the notification to the user. The notification always uses the same sound that was initially established when the service was first started and never becomes immediately visible to the user without sliding the notification tray down from the top of the screen.
What does seem to work is that I create a separate notification channel for this one case, but then I have two different notification items in the tray. Another way that appears to work is shown on YouTube # https://www.youtube.com/watch?v=3Je9ZEAAjfA where the author uses NotificationManager.deleteNotificationChannel to remove, then NotificationManager.createNotificationChannel however, they said the OS will eventually delete my app if I keep re-creating the notification channel as some form of spam prevention.
Is there some way to reuse the original notification channel to dynamically change the sound and make it visible?
I'll go out on a limb and show the solution I chose. The createNotificationChannels method gets called during onCreate, then createNotification gets called once at onStartCommand to satisfy the 5 second limit for calling startForeground. Then I call createNotification, as needed, to select which of the 3 different channels to display and set the title/body contents. I'd sure rather be able to dynamically set the sound.
private int CHANNEL_NOTIFICATION_ID = 666;
public static final String TARGET_MESSAGING_GROUP_ID = "TargetMessagingGroupID";
public static final String TARGET_MESSAGING_GROUP_NAME = "Target Messaging Group";
public static final String WAITING_NEW_TARGET_CHANNEL_ID = "WaitingNewTargetChannelID";
public static final String WAITING_NEW_TARGET_CHANNEL_NAME = "Waiting for New Target Channel";
public static final String NAVIGATING_TO_TARGET_CHANNEL_ID = "NavigatingToTargetChannelID";
public static final String NAVIGATING_TO_TARGET_CHANNEL_NAME = "Navigating To Target Channel";
public static final String TARGET_ARRIVAL_CHANNEL_ID = "TargetArrivalChannelID";
public static final String TARGET_ARRIVAL_CHANNEL_NAME = "Target Arrival Channel";
// --------------------------------------------------------------------
// Method: createNotificationChannels
//
// Purpose: Called once at startup so we have the notification channels
// ready to go when we need them
// --------------------------------------------------------------------
protected void createNotificationChannels()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
// use the same audio attributes for each channel
AudioAttributes audioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build();
// configure the group
NotificationChannelGroup targetMessagingGroup = new NotificationChannelGroup(TARGET_MESSAGING_GROUP_ID, TARGET_MESSAGING_GROUP_NAME);
// configure the first channel
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + parentContext.getPackageName() + "/" + R.raw.elevatording);
NotificationChannel waitingNewTargetChannel = new NotificationChannel(WAITING_NEW_TARGET_CHANNEL_ID, WAITING_NEW_TARGET_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
waitingNewTargetChannel.setDescription(WAITING_NEW_TARGET_CHANNEL_NAME);
waitingNewTargetChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
waitingNewTargetChannel.setSound(soundUri, audioAttributes); // This is IMPORTANT
waitingNewTargetChannel.enableLights(true);
waitingNewTargetChannel.setLightColor(Color.RED);
waitingNewTargetChannel.enableVibration(false);
waitingNewTargetChannel.setGroup(TARGET_MESSAGING_GROUP_ID);
// configure the second channel
soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + parentContext.getPackageName() + "/" + R.raw.beep);
NotificationChannel navigatingToTargetChannel = new NotificationChannel(NAVIGATING_TO_TARGET_CHANNEL_ID, NAVIGATING_TO_TARGET_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
navigatingToTargetChannel.setDescription(NAVIGATING_TO_TARGET_CHANNEL_NAME);
navigatingToTargetChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
navigatingToTargetChannel.setSound(soundUri, audioAttributes);
navigatingToTargetChannel.enableLights(false);
navigatingToTargetChannel.setLightColor(Color.RED);
navigatingToTargetChannel.enableVibration(false);
navigatingToTargetChannel.setGroup(TARGET_MESSAGING_GROUP_ID);
// configure the third channel
soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + parentContext.getPackageName() + "/" + R.raw.purge_siren_loud);
NotificationChannel targetArrivalChannel = new NotificationChannel(TARGET_ARRIVAL_CHANNEL_ID, TARGET_ARRIVAL_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
targetArrivalChannel.setDescription(TARGET_ARRIVAL_CHANNEL_NAME);
targetArrivalChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
targetArrivalChannel.setSound(soundUri, audioAttributes); // This is IMPORTANT
targetArrivalChannel.enableLights(true);
targetArrivalChannel.setLightColor(Color.RED);
targetArrivalChannel.enableVibration(true);
targetArrivalChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
targetArrivalChannel.setGroup(TARGET_MESSAGING_GROUP_ID);
// finally, register the group and associated channels with the OS
NotificationManager notificationManager = (NotificationManager) getSystemService(NotificationManager.class);
notificationManager.createNotificationChannelGroup(targetMessagingGroup);
notificationManager.createNotificationChannel(waitingNewTargetChannel);
notificationManager.createNotificationChannel(navigatingToTargetChannel);
notificationManager.createNotificationChannel(targetArrivalChannel);
}
}
// --------------------------------------------------------------------
// Method: createNotification
//
// Purpose: Called whenever changing the displayed notification is
// required. Must call this with requestedNotificationType
// of NOTIFY_TYPE_WAITING_FOR_TARGET from onStartCommand
// in order to call startForeground within the 5 second limit
// for a foreground service.
// --------------------------------------------------------------------
protected void createNotification(LocationService.LocationNotifyType requestedNotificationType, Bitmap notificationBitmap, Uri soundUri, String title, String message)
{
Intent notificationIntent = new Intent(parentContext, signalledClass);
PendingIntent pendingIntent = null;
Notification notification = null;
int notification_id = CHANNEL_NOTIFICATION_ID;
switch (requestedNotificationType)
{
default:
{
Log.d("LocationHandler", "Unknown LocationNotifyType, NOT changing notification");
break;
}
case NOTIFY_TYPE_WAITING_FOR_TARGET:
{
pendingIntent = PendingIntent.getActivity(parentContext, 0, notificationIntent, 0);
notification = new NotificationCompat.Builder(parentContext, WAITING_NEW_TARGET_CHANNEL_ID)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(notificationBitmap)
.setPriority(NotificationCompat.PRIORITY_HIGH) // only affects API 25 and below
.setStyle(new NotificationCompat.BigTextStyle().setSummaryText("Waiting").setBigContentTitle(title).bigText(message))
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.setSound(soundUri)
.build();
if (notification != null)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
startForeground(notification_id, notification);
}
else
{
NotificationManagerCompat.from(parentContext).notify(notification_id, notification);
}
}
break;
}
case NOTIFY_TYPE_NAVIGATING:
{
pendingIntent = PendingIntent.getActivity(parentContext, 0, notificationIntent, 0);
notification = new NotificationCompat.Builder(parentContext, NAVIGATING_TO_TARGET_CHANNEL_ID)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(notificationBitmap)
.setPriority(Notification.PRIORITY_HIGH) // only affects API 25 and below
.setStyle(new NotificationCompat.BigTextStyle().setSummaryText("Navigating").setBigContentTitle(title).bigText(message))
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.setSound(soundUri)
.build();
NotificationManagerCompat.from(parentContext).notify(notification_id, notification);
break;
}
case NOTIFY_TYPE_ARRIVAL:
{
notificationIntent.setAction("ArrivalNotification");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
notificationIntent.putExtra(AllConstants.APP_WAKEUP_TYPE, AllConstants.APP_WAKEUP_TARGET_ARRIVAL);
pendingIntent = PendingIntent.getActivity(parentContext, notification_id, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification = new NotificationCompat.Builder(parentContext, TARGET_ARRIVAL_CHANNEL_ID)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(notificationBitmap)
.setPriority(NotificationCompat.PRIORITY_HIGH) // only affects API 25 and below
.setStyle(new NotificationCompat.BigTextStyle().setSummaryText("Arrival").setBigContentTitle(title).bigText(message))
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.setSound(soundUri)
.setWhen(System.currentTimeMillis())
.build();
NotificationManagerCompat.from(parentContext).notify(notification_id, notification);
break;
}
}
}

How clean notification when close app like spotify?

I have a service for radio, that show a notification to identify stop and playing, but when I kill the application by swipe, I can't clear the notification
PendingIntent openAppIntent = PendingIntent.getActivity(RadioService.this, 0, new Intent(RadioService.this, GeneralActivity.class), 0);
Notification notification = new NotificationCompat.Builder(RadioService.this)
.setSmallIcon(R.drawable.ic_pause_lx)
.setContentTitle(getResources().getString(R.string.radio) + " " + getResources().getString(R.string.app_name))
.setAutoCancel(true)
.setContentIntent(openAppIntent)
.addAction(android.R.drawable.ic_media_pause, getString(R.string.stop), PendingIntent.getBroadcast(RadioService.this, 0, new Intent(ACTION_PAUSE), 0))
.addAction(0, getString(R.string.open), openAppIntent)
.build();
mNotificationManager.notify(NOTIFICATION_ID, notification);
registerReceiver(mActionsReceiver, new IntentFilter(ACTION_PAUSE));
Call this in you activity's onDestroy():
NotificationManager ntfManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
ntfManager.cancelAll();

Notification manager has stopped working

This issue has been solved. See my solution below.
I just completed converting my messaging app to FCM. You can see the process I have been through here. Now that it is done, my notifications no longer work. If my FirebaseMessagingService gets a message and the main app is not active, I create a notification on the phone I'm running on.
This has been running for years correctly on GCM. When I trace through the code, it all executes ok - just no notification shows up in the tray. I can't imagine what Firebase would have to do with this.
This is the code that gets called from the FirebaseMessagingService. This code has been running for years just fine . . .
public static void raiseNotification( String username, String mesText, int count)
{
String message = "From: " + username + " " + mesText;
if (count > 1)
{
count--;
message = message + " + " + count + " more";
}
NotificationCompat.Builder b = new NotificationCompat.Builder(GlobalStuff.GCT);
Intent intent = new Intent(GlobalStuff.GCT, MainActivity.class);
intent.putExtra("whattodo", username);
intent.setAction(Long.toString(System.currentTimeMillis())); //just to make it unique from the next one
PendingIntent pIntent = PendingIntent.getActivity(GlobalStuff.GCT, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
b.setContentTitle("New SafeTalk Message")
.setSmallIcon(R.drawable.ticon)
.setContentText(message)
.setTicker("New SafeTalk Message")
.setContentIntent(pIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true);
//.addAction(R.drawable.smallredball, "Read Now", pIntent)
//.addAction(R.drawable.smallquestion, "hello there", pIntent);
NotificationManager mgr = (NotificationManager)GlobalStuff.GCT.getSystemService(NOTIFICATION_SERVICE);
mgr.notify(0, b.build());
}
This issue is solved. Once you write an app for Android, Google will have you working full time for the rest of your life just to keep it working. They are breaking change demons. Turns out this notification problem has nothing to do with Firebase (which is itself the mother of all breaking changes).
Google changed the requirements on how to send a notification in Oreo. Google designed this change so that if your app is running on Oreo and you haven't made the change your notification simply won't work - hope nobody was building notifications that were important. In Oreo they require a channelId.
Here is code that works in Oreo . . .
Actually this code does not completely work in Oreo. See my next post regarding notifications in Oreo
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

How to make push notification with specific sound?

I'm working on android app with system of notifications and i need the android device to push the notification with a specific sound i stored on assets folder
this is my java code for notification :
Notification noti = new Notification.Builder(MainActivity.this)
.setTicker("Calcupital")
.setContentTitle("Calcupital")
.setContentText("User Information has been updated successfully")
.setSmallIcon(R.drawable.login)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
Assuming that my sound stored like that : (\assets\hopo.mp3)
how to make this notification pushed with this sound without changing the push notification systems for other apps by changing the sound from the list that android device offered !!.
I hope my question is very clear to you :)
To combine the answers here and using the two answers from these questions:
How to add sound to notification?
How to get URI from an asset File?
Try this:
Uri sound = Uri.parse("file:///android_asset/hopo.mp3");
Notification noti = new Notification.Builder(MainActivity.this)
.setTicker("Calcupital")
.setContentTitle("Calcupital")
.setContentText("User Information has been updated successfully")
.setSmallIcon(R.drawable.login)
.setSound(sound);
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
You need to place your sound file to res/raw directory.
Then add this code into current code
final String packageName = context.getPackageName();
notification.sound =
Uri.parse("android.resource://" + packageName + "R.raw.hopo");
see this link for more details
http://developer.android.com/reference/android/app/Notification.Builder.html#setSound(android.net.Uri)
you can set default sound using
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alarmSound != null) {
mBuilder.setSound(alarmSound);
}
if you want custom sound just use different Uri. how to get Uri from assets? check this topic
To get the resource:
Uri alarmSound = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.somefile);
** the raw folder must be created inside res folder and add youre sound file **
To set up:
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
.setContentText(message)
.setSound(alarmSound) // -> add this one
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });

Notification sound not playing

I know this question has been asked many times, but I'm still having issues getting it working.
In my application, I create a notification to prompt the user of some event and I'd like to play a sound that has been packaged as a raw resource within the application.
I create my notification instance:
Notification notification = new Notification(
R.drawable.some_image,
"some meaningful name",
System.currentTimeMillis() );
notification.setLatestEventInfo(...)
Then set some attributes on that notification:
notification.sound = Uri.parse( "android.resource://com.my.package/" + R.raw.some_mp3_file );
notification.flags = Notification.FLAG_INSISTENT;
Finally I invoke the NotificationManager to display the notification:
notificationManager.notify( 1, notification );
The notification does shows up, but the sound doesn't play.
Am I doing something wrong? Is there a <uses-permission> I'm missing? I can't see anything that I've done differently from anyone else that seems to have gotten it working.
For what it's worth, I'm testing directly on a Nexus 7.
try to look at below code. may help you out to solve your problems.
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.update;
CharSequence tickerText = "assignments";
long when = System.currentTimeMillis();
Notification assignmentNotification = new Notification(icon, tickerText, when);
**For sound** assignmentNotification.defaults |= Notification.DEFAULT_SOUND;
long[] vibrate = {0,100,200,300};
**For vibrate** assignmentNotification.vibrate = vibrate;
Context context = getApplicationContext();
CharSequence contentTitle = "check assignments";
CharSequence contentText = "chek ur app for assignments ";
Intent notificationIntent = new Intent(context, ViewAssignmentnotificationActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,0);
assignmentNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
** final int id = 2;
Please see this answer; It tells you that you have to explicitly specify notification.sound to play that tone;

Categories

Resources