If I create a regular notification without sound, it works correctly. But if I add a sound, it vibrates. This is illogical so I don't understand it.
Here is an example of the code that works correctly (doesn't vibrate)
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0))
.setOngoing(false);
builder.setCategory(Notification.CATEGORY_SERVICE);
builder.setVisibility(Notification.VISIBILITY_SECRET);
builder.setPriority(Notification.PRIORITY_MAX);
builder.setLights(0xFF00FF00, 1000, 0);
Uri theUri = Uri.parse(uriString);
//builder.setSound(theUri);
builder.setContentText("Android sucks");
builder.setAutoCancel(false);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(FOREGROUND_ID, builder.build());
Here is the code that causes the phone to vibrate. Notice that vibration is NOT set in my notification:
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0))
.setOngoing(false);
builder.setCategory(Notification.CATEGORY_SERVICE);
builder.setVisibility(Notification.VISIBILITY_SECRET);
builder.setPriority(Notification.PRIORITY_MAX);
builder.setLights(0xFF00FF00, 1000, 0);
Uri theUri = Uri.parse(uriString);
builder.setSound(theUri);
builder.setContentText("Go buy an iPhone");
builder.setAutoCancel(false);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(FOREGROUND_ID, builder.build());
Call me irrational, but when I want the sound I'll set the sound and when I want vibration, I'll set the vibration. If I want both, I'll set both. So why is it that when I set the sound, I automatically get vibration?
This seemed to do the trick:
long[] nullify = {0,0,0};
builder.setVibrate(nullify);
Although it lead to a number of additional frustrating anomalies. There are seven audio streams. They are:
STREAM_RING;
STREAM_NOTIFICATION;
STREAM_ALARM;
STREAM_MUSIC;
STREAM_DTMF;
STREAM_SYSTEM;
STREAM_VOICE_CALL;
Now, if I had to choose which stream I thought the notification sound would use, which stream do you think I'd guess? You are correct, I expect it to use STREAM_NOTIFICATION. What stream does it use? STREAM_SYSTEM. So if I want to be able to control the volume of my notification, I have to set the volume for STREAM_SYSTEM. But that of course has unwanted side effects like now that I changed that setting you can hear an audible sound when I click "like" on something in the facebook app, for example.
Android is crazy messed up.
Related
I am simultaneously developing two Android applications that are communicating with each other, and I am using notifications to show received messages. This is the code I am using to show a notification:
private void showNotification(String title, String content) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"NOTIF_CHANNEL",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("CHANNEL FOR INFORMING ABOUT MESSAGE RECEIVED");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "default")
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle(title) // title for notification
.setContentText(content)// message for notification
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI) // set alarm sound for notification
.setAutoCancel(true); // clear notification after click
Intent intent = getPackageManager()
.getLaunchIntentForPackage(getPackageName())
.setPackage(null)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder.setContentIntent(pi);
mNotificationManager.notify(0, mBuilder.build());
}
In one of my applications, this works flawlessly every time, but in the other it never works. I am using the exact same code and running the applications on the same device.
I am curious as to if someone is able to identify or make a guess on factors that would make a difference here. I have tried using the same icon, title, content, and sound, but to no avail. Any help or suggestions would be greatly appreciated!
If your code is working in one app but not in the other, and the code is exactly the same, surely you are using distinct versions of support library and/or distinct targetSdkVersion. Set the same of the app which works in the other that doesn't works.
I'm implementing local notification on Android and I have the problem that they are not appearing on Android 6.0 (Samsung S7).
I was searching for solutions, but I coulnd't find anything for this problem. I have the icon in the proper res/drawable folder, also I have defined a notification title, text, ringtone (raw folder) but it's not showing up...
There is my code:
Context acontext = getApplicationContext();
PackageManager pm = acontext.getPackageManager();
Intent notificationIntent = pm.getLaunchIntentForPackage(acontext.getPackageName());
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(acontext, 0, notificationIntent, 0);
int notification_icon = acontext.getResources().getIdentifier("icon", "drawable", acontext.getPackageName());
int notificationID = 0;
// Build notification
Notification noti = new Notification.Builder(acontext)
.setContentTitle("Title")
.setContentText("Incoming text")
.setSmallIcon(notification_icon)
.setContentIntent(pendingIntent)
.setLights(Color.RED, 1, 1)
.build();
NotificationManager notificationManager = (NotificationManager) acontext.getSystemService(Context.NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.sound = Uri.parse("android.resource://" + acontext.getPackageName() + "/raw/incoming");
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notificationID, noti);
Did anyone else experience this problem? Any help would be appreciated. Thank you.
There are some changes in new notification. new NotificationCompat.Builder(this) is deprecated and need NotificationChannelfor android oreo above. You can try this solution.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Title");
bigText.setSummaryText("Text in detail");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
NotificationManager mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, mBuilder.build());
There are various layers involved in showing notifications in Android, Please first check if this works for other devices of same OS version. Normally these kind of issues are device specific not OS specific, Also check notification logs how to check notification logs in android ?
If issue is device specific, following can be handy tips:
Check notifications not blocked for your app by device settings.
Check power settings blocking non-priority notifications.
If there are notifications in logs but not showing up, there can be some issue with your internal OS settings/configs. (believe me Android is not very clean OS)
If you can, try factory resetting your device. (In my case this worked)
Google Play Services must be enabled in order to receive push notifications on your Android device. If Google Play Services are enabled and the general troubleshooting steps have not resolved the issue, it may be necessary to reset the app. To reset the app, go to Settings → Apps → PagerDuty and tap Clear Data.
For Android 6.0 and newer, make sure the app is set as a prioritized app in priority mode.
For Android 6.0 and newer, check to see if the app is being silenced by Doze mode.
Check the android version accordingly set the icon for > 6.0 and for other.For 6.0 version we need white background icon.
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
icon = R.mipmap.your_logo_for_Lolipop;
}else{
icon = R.drawable.your_logo_for_Kitkat ;
}
How can I send a notification with sound and vibration when phone is in do not disturb mode on Android Devices.
I use the following code, and it is working when my application is currently in foreground.
PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID,
resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText("You've received new message."))
.setContentText("You've received new message.");
// FOR SILENT MODE
AudioManager am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
// For Normal mode
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
mBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
// defaults = defaults | Notification.DEFAULT_VIBRATE;
// defaults = defaults | Notification.DEFAULT_SOUND;
mBuilder.setDefaults(defaults);
mBuilder.setSound(Uri.parse("android.resource://" + getPackageName()
+ "/" + R.raw.siren));
// Cancel the notification after its selection
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
I also want notifications with sound and vibration when my app is in background.
Generally speaking you can't. Even notification with MAX priority wont be shown in DND mode.
The possible workaround that I can imagine is to use android.permission.SYSTEM_ALERT_WINDOW to draw custom notification over system window (FB Messanger works in similar way) : Creating a system overlay window (always on top) .
But this method is suitable only in rare cases and most of the time it's a violation of Android UI/UX best practices.
Ok good news you are half way there.
I achieved this previously by using AudioManager & VIBRATOR_SERVICE (yea I know ;)
The idea is not to use NotificationCompat.Builder because it will rely on system settings and if device is in silent mode, it won't vibrate nor play sound. You have to manually play a sound using AudioManager & vibrate using VIBRATOR_SERVICE.
You are using AudioManager & setting the properties but you are never actually asking it to play the sound. So, in your code its never actually utilized.
Here's an example of how to play a sound using AudioManager, it will also ignore silent mode:
Here's an example of using VIBRATOR_SERVICE:
Combine these 2 approaches and ditch NotificationCompat.Builder
If you can get right permissions to change settings of device, then you could show notifications with sound and vibration at your apps. Also check this out.
i have an application about football/soccer , i'm using API for get information about the matches, i need a way to make a real time notification when a goal is added in this API which have a JSON format .
If you have access to your back end web service code, look into Google cloud messaging(gcm) service, it is made precisely for this purpose. If it is not feasible to use gcm, you need to set a repeating alarm, but it will not be as accurate as gcm. But I highly recommend going for gcm. Here's a link for your reference. GCM dev docs
Another work around for the case where you don't have access to source code for back end is to develop a middle layer sort of web service that keeps polling your back end and uses gcm to alert the clients. This way atleast you won't be wasting user's system resources.
This is how you pop a notification:
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo_notification)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(new long[] { 200, 200, 200})
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build()); //id is the notification id, if you use the same id, the notification will override the previous
In order to achieve the functionality,
Use a service to frequently(maybe once in 5 minutes) check information about the match.
If you have any Updates, show a notification to the user.
To show Notification:
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
Notification notification = new NotificationCompat.Builder(getApplicationContext()).setTicker("Ticker Text").setSmallIcon("Icon").setContentTitle("Title").setContentText("Content Text").setContentIntent(pi).setAutoCancel(true).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
For more info use this link
here
What you really want to do is have a Receiver that will run and check for updates. For real time updates, I would use a Socket.
It pretty much depends on your server.
I'm trying to use the LED on my notification and it's not working, i have this code:
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(getApplicationContext());
nBuilder.setLights(Color.CYAN, 1000, 500);
The entire notification is working, like ContentTitle, ContentText and the notification is shown, but only the LED is not working.
Is there anything wrong with my code ? Should i use the Notification instead NotificationCompact.Builder ?
The LED light for notifications is turned on by the OS in the device only if the notification is triggered while the device screen is off.
Your code can not work, because you have to pass three variables:
the color
if turning on the led is on
if turning off the led is on
if you enable 2 and 3 your led will be blinking, if you disable 2 and 3 the led will be turned off
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context );
mBuilder.setLights(Color.RED, 1, 1); // will blink
That code seems OK, for the APIs before 26.
You might try adding Notification.FLAG_SHOW_LIGHTS
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context);
nBuilder.setLights(Color.CYAN, 1000, 500);
Notification notif = nBuilder.build();
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(0, notif);
Also make sure that you do not swipe down to preview the notification, otherwise the LED will be off when the display goes black.