In Lollipop and below, you could easily send a sound only notification by omitting the icon, content title and content text when constructing, like so:
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setSound(Uri.parse(ringtone));
notificationManager.notify(9998, builder.build());
In Marshmallow, I'm forced to include at least an icon, or I get a 'no valid small icon' exception. I want to use the Notification system, but don't always want to display a notification in the notification bar. Is this possible with Marshmallow, or should I change to playing my notification sound with media player, even though sometimes I, or the user, may want to display a notification?
I read somewhere that the docs said icon was required even thought it didn't throw an exception when omitted in Lollipop and below. After looking into using MediaPlayer, I finally decided to use RintoneManager to play it. I am using the notification sounds, so may as well save myself some typing and do a quick
try {
RingtoneManager.getRingtone(getApplicationContext(), Uri.parse(ringtone)).play();
} catch (Exception e) {
e.printStackTrace();
}
to trigger the sound, I'll save the notification for when I need an actual notification. I was already planing on using if, depending on whether or not the notification should appear in the notification bar.
Related
I have made an android app (Android Studio / Java) that checks a website for content and stores it in an sqlite DB. If new content is fetched that is not stored in DB, it shows a notification with the new content for user to notice.
That's working fine, although if user does not read/open/dismiss that notification, the next notification will update current one and replace its content with new data. This is wanted behavior, because I don't want the user to receive many notifications for the same thing, so I'm using the same notification id.
This introduces a problem though, if user checks the notification now, he will see the second fetched data, but won't be aware of the existence of the first fetched data.
So, what I'm trying to do is to append to the notification's content, so that both first and second fetched data are shown.
I tried the "inboxStyle" notifications that allow for new lines to be added, but it seems to be working only for setting many lines at the time notification is created and not for appending lines to an existing notifications.
I know that I can do that by storing what user has seen and what not, whether a notification was opened, etc, but this seems too much hassle for a simple thing, there must be an easier way to achieve it.
The expected behavior would be to either be able to append the message of existing notifications, or be able to fetch the message of an existing notification (by id) and then manually append to it and push the updated notification.
If that's not clear enough, the expected outcome is:
Issue the first notification with message "Test message 1"
Issue second notification using the same notification-id with message "Test message 2" that would NOT overwrite "Test message 1" but rather keep that message and append to it, so that the notification's message would now be "Test message 1 {newline-here} Test message 2" (or even better reversed so that the last message is shown on top).
Thank you in advance!
I was looking for a solution myself. I managed to do something that works but I'm quite sure there are other elegant solutions : I'm checking whether or not similar notification has been displayed. If so, I get the previous content and append it to the new notification content before publishing.
First, make sure that the notifications you want to assemble have the same uniqueID
This way, when you receive your 2nd, 3rd notification, you can easily match the one you are creating with the ones already displayed.
Note : This code works only on API 23 and higher.
String message = null;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
StatusBarNotification[] notifications = mNotificationManager.getActiveNotifications();
for (StatusBarNotification notification: notifications) {
if (notification.getId() == uniqueID) {
// You have a match
Bundle extras = notification.getNotification().extras;
message = extras.getCharSequence(Notification.EXTRA_TEXT).toString();
break;
}
}
}
The easy part : Now that you have the previous notification text, you have to append it to the new notification text before publishing
String newMessage = message + remoteMessage.getData.get("text");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(),
channelID)
.setStyle(new NotificationCompat.BigTextStyle().bigText(newMessage))
.setContentTitle("Title")
.setContentText(notification.getMessage())
.setAutoCancel(true);
I am building out a media player for Android Auto and struggling to make a simple Toast Message that appears on the Automotive Display Head Unit.
In my Custom Actions, I have an action that needs to display a toast message on the Car interface, but when I implement the toast it instead only shows on the handheld device/phone.
I have searched the internet high and low, and can not find anything about displaying toasts on the Car Head Unit, even though it is listed in the Android Auto Design guide:: https://designguidelines.withgoogle.com/android-auto/android-auto/app-ui.html#app-ui-drawer
could someone please point me to an example for giving visual feedback or toasts on the Android Auto Platform?
You cannot.
If you have a look at the following question: Develop an Android Auto custom app I have shared a jar which allows you to use some of the un-offical Android Auto SDK from there you can import this:
import com.google.android.apps.auto.sdk.CarToast;
import com.google.android.apps.auto.sdk.notification.CarNotificationExtender;
However even if you import the classes and use the CarToast like this:
CarToast.makeText(context,"SPEED CAMERA: " + text, Toast.LENGTH_LONG).show();
it will only display the toast on the phone screen not on the projected screen.
So to display a message correctly you will need to do something like this:
CarToast.makeText(context,"SPEED CAMERA: " + text, Toast.LENGTH_LONG).show();
CarNotificationExtender paramString2 = new CarNotificationExtender.Builder()
.setTitle(title)
.setSubtitle(text)
.setShouldShowAsHeadsUp(true)
.setActionIconResId(R.drawable.ic_danger_r)
.setBackgroundColor(Color.WHITE)
.setNightBackgroundColor(Color.DKGRAY)
.setThumbnail(bmp)
.build();
NotificationCompat.Builder mynot = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(text)
.setLargeIcon(bmp)
.setSmallIcon(R.drawable.ic_danger_r)
.setColor(Color.GRAY)
.extend(paramString2);
mNotifyMgr.notify(1983,mynot.build());
This will show a toast which will only be visible on the phone screen and it will show a heads-up notification which will only be visible on the car's screen. Since there is no action attached to it, nothing will happen if the use interacts with it the notification.
If the phone is connected to the car the phone's screen will be turned off anyway so displaying Toast there will be ignored.
The problem with all this is that since it's an unofficial jar and the SDK is not available to the public you won't be able to publish the app on PlayStore :(, that being said I only tried to publish complete apps, but an app which just display notification might pass through the filter.
Tried to show 3 notification in cluster format. As per the doc, I added the setGroupSummary(true) property for the first notification.But in the result i have got only two notification. The notification which is added the GroupSummary property is not visible.
NotificationCompat.Builder firstNotification = createNotification(context,"1.Message","Here you go 1");
firstNotification .setGroupSummary(true);
firstNotification .setGroup("KEY_NOTIFICATION_GROUP");
NotificationCompat.Builder secondNotifi = createNotification(context,"2.Message","Here you go 2");
secondNotifi .setGroup("KEY_NOTIFICATION_GROUP");
NotificationCompat.Builder thirdNotifi= createNotification(context,"3.Message","Here you go 3");
thirdNotifi.setGroup("KEY_NOTIFICATION_GROUP");
Here the notification trigger,
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,firstNotification .build());
notificationManager.notify(1,secondNotifi .build());
notificationManager.notify(2,thirdNotifi.build());
And the result is,
I want to show all three notification in the cluster format without missing.
Any help will be really appreciated.
You should check the following answer :
setgroup() in notification not working
You have to create a separate group notification and set the group summary flag true only for that, and that becomes the parent notification that bundles other notifications with the same group key within itself.
setGroupSummary's purpose is to support API levels below Nougat. On Android 7.0 and higher, it shows a normal group and just uses the on click behavior (setContentIntent) and details like the summary text of the summary notification.
On Android 7.0 and lower, it shows your summary notification as a replacement for all the other notifications the group contains.
Android 7 makes a decision regarding summary notification is shown by itself. So, you want see it unless system decides that it needs to be displayed.
Solution: create a dedicated summary notification.
On Android L, I would like show the user a notification on the lock screen only if the user settings is set to "show all notification content", otherwise the content will be pointless and I just prefer not to show the notification at all.
Any idea how to verify in code the user notification settings?
Thanks!
You need to read
Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS = "lock_screen_allow_private_notifications"
Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS = "lock_screen_show_notifications"
only if both are 1 then you need to show your notifications.
But since these values are not part of public api, these might change in future, or might not work on all devices
int show_all = Settings.Secure.getInt(getContentResolver(),"lock_screen_allow_private_notifications", -1);
int noti_enabled = Settings.Secure.getInt(getContentResolver(),"lock_screen_show_notifications", -1);
if(show_all > 0 && noti_enabled > 0){
//post noti
}
You can't check that setting as far as I know, but your app can control the level of detail visible when its notifications are displayed over the secure lock screen. To control the visibility level, call setVisibility() (Notification.Builder.setVisibility) and specify one of these values:
VISIBILITY_PUBLIC: Shows the notification’s full content.
VISIBILITY_PRIVATE: Shows basic information, such as the notification’s icon, but hides the notification’s full content.
VISIBILITY_SECRET: Shows nothing, excluding even the notification’s icon.
When the visibility level is VISIBILITY_PRIVATE, you can also provide a redacted version of the notification content that hides personal details. For example, an SMS app might display a notification that shows "You have 3 new text messages" but hides the message content and senders. To provide this alternative notification, first create the replacement notification using Notification.Builder. When you create the private notification object, attach the replacement notification to it through the setPublicVersion() method.
Sources
I have searched for this, so apologies if this has been answered already (I am happy to be redirected), but specifically our issue is intermittent.
Our clients are complaining that the notification audio is, intermittently, not 'chiming' when an event is sent to their phones from our software. It will work fine for a time, then 'just stop for a few hours' (extrapolating from the complaints of our customers).
We've not been able to reproduce this in house, but the frustration we are getting from our customers is such that we really need to fix it.
Our customers insist they are not making phone calls, playing audio or running other software, and from seeing their phones, I largely believe them.
We have noticed this largely on Jellybean, as this is what most of our clients are running, however it may not be isolated to this case.
Am I doing something wrong, or is there a better way to 'chime' for a notification. At this stage I am happy to try something different
void updateNotification()
{
Notification.Builder builder = new Notification.Builder(_context);
// Set the appearance of the notification:
int icon;
String title;
String description;
// ...
//CODE setting icon, title and description
// ...
builder.setSmallIcon(icon);
builder.setContentTitle(title);
builder.setContentText(description);
builder.setTicker(description);
// Set the sound for the notification:
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));
Intent intent = new Intent(_context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(MainActivity.EXTRA_TAB, MainActivity.EXTRA_TAB_TASKS);
builder.setContentIntent(PendingIntent.getActivity(_context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
// Update the notification:
NotificationManager manager = (NotificationManager)_context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(_notificationId, builder.build());
}
For some reason, I noticed some devices mute all volumes (including the alarm volume) when they are put on silent or vibrate mode. And in those modes, for these devices, this volume can't be changed unless you change the mode.
I had users complaining of a similar problem and had to handle it by forcing a change of mode to ensure the volume is high enough. I then played the audio and switched the mode back to the original configuration.
Edit: Here is a post from a user complaining about this. Notice on the screenshot there that the volume button for "alarms" is disabled on mute.
Edit 2: In my particular case, I run the following check to see if I need to increase the volume:
if (audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL
&& audioManager.getStreamVolume(AudioManager.STREAM_ALARM) == 0) {
// Save current state and increase the volume
}
Whilst the answer #Ricardo gave is certainly worth including in your code, and I have left it in ours, my problem was largely due to the phone's power-management (this may have been obvious, but I'm newish to Android development).
Our notifications are required to be delivered when sent, and our user's phones were going into sleep mode, so we added a WakeLock (though, caring for their battery life, we only have it 'on' when the user was 'Signed In' to our app. At the end of their shift, the WakeLock was released).