Show notification automatically - android

I am using this code to show a notification on my smartwatch:
Notification n = new Notification.Builder(this)
.setContentTitle("Message")
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.icon))
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
How can I show it automatically on my smartwatch screen when it is created? Thanks.

it called Heads-up notifications
per developer site : you can use it if:
The user's activity is in fullscreen mode (the app uses
fullScreenIntent).
The notification has high priority and uses ringtones or vibrations on
devices running Android 7.1 (API level 25) and lower.
The notification channel has high importance on devices running
Android 8.0 (API level 26) and higher.
so what you need to do is adding this :
builder.setPriority(Notification.PRIORITY_MAX);

Why don't you try this.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Message")
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.icon));
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(UPDATE_NOTIFICATION_ID, builder.build());

Related

Notification Count not shown Badges in App Launcher Icon in Android Version 29 and 27

I want to show unread messages count on my android app's launcher icon. It should be cleared only once the user read all messages. I have tried setnumber() in NotificationCompat.Builder. But it is not showing the notification count.
I executed my code in two android devices.
Real Android device - version is 29 (red dot appeared in app launcher when i generate notification)
Android Emulator - version is 27 (nothing is shown)
Notification Channel Creation:
private void createNotificationChannel(String notificationChannelId, String systemTrayNotificationName){
Log.i("Tag","createNotificationChannel "+Build.VERSION.SDK_INT);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence name = systemTrayNotificationName;
String description = systemTrayNotificationName;
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, name,importance);
notificationChannel.setDescription(description);
notificationChannel.setShowBadge(true);
notificationChannel.canShowBadge();
NotificationManager notificationManager = getContext().getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
}
Code to form notification
public void buildNotification(){
createNotificationChannel(NOTIFICATION_CHANNEL_ID,SYSTEM_TRAY_NOTIFICATION_NAME);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_home_black_24dp)
.setLargeIcon(BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ic_launcher))
.setContentTitle("Title")
.setContentText("Content Text")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setNumber(5)
.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE)
.setAutoCancel(true);
// Get an instance of the NotificationManager service
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getContext());
// Issue the notification with notification manager.
notificationManager.notify(200, notificationBuilder.build());
}
The number of notifications must be supported by the launcher you are using.
As far as I know, the pixel launcher typical of google phones and present by default as launcher3 of the emulators does not support the notification count exactly as it happens in your first case.
You could try with a third party launcher to see if the counting works but as just said this feature must be natively supported by the launcher.

Wear OS: notifications won't show

I am developing a stand alone app on Wear OS (Android 8+) and I have issues with notifications.
I am running a Foreground Service, with an on-going notification. That on-going notification works very well and has no feature from the Wear OS (so the code can work on standalone Android).
However, whenever I want to display other notifications, it is impossible.
No error message, nothing: my notifications are not displayed.
I made sure to create separate channels and to have them enabled (via the settings).
Here is my code, running in the Looper.mainLooper() via a Handler.
final Notification notification = new NotificationCompat.Builder(MonitorService.this, LOGS_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_backup_logs) // vector (doesn't work with png as well)
.setContentTitle(getString(R.string.monitor_service_notification_log_file_backed_up_process))
.setContentText("test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build();
notificationManagerCompat.notify(LOGS_ID, notification); // unique final static id
Am I missing something here ?
Thanks for the help !
Use this code
Notification.Builder b = new Notification.Builder(ctx);
//FIX android O bug Notification add setChannelId("shipnow-message")
NotificationChannel mChannel = null;
b.setSmallIcon(R.drawable.ic_backup_logs) // vector (doesn't work with png as well)
.setContentTitle(getString(R.string.monitor_service_notification_log_file_backed_up_process))
.setContentText("test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel = new NotificationChannel("your-channel", "yourSubjectName",NotificationManager.IMPORTANCE_HIGH);
b.setChannelId("your-channel");
}
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(id, b.build());

How to create a Android notification with support to older API levels (e.g. lvl 23)

Maybe this issue is way simpler than I expected it to be: I want to display a notification, created within the onCreate function of an Activity (for debugging reasons).
Android Studio 3.0.1, Api lvl 23 (to support older devices) and running on a Nexus5 device with Api lvl 27.
The Code to display a notification:
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification notification = new NotificationCompat.Builder(this)
.setTicker("SomethingTicker")
.setSmallIcon(R.drawable.someImage)
.setContentTitle("SomeTitle")
.setContentText("SomeText")
.setContentIntent(pi)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(001, notification);
Which shows that NotificationCompat.Builder with only the the context is deprecated. I should use a Notification Channel within the newer version.
The issue: To create and register a NotificationChannel I have to use api lvl >27.
What am I missing? And what is the best way
I want to display a notification, created within the onCreate function of an Activity.
Note that this is an odd time to display a Notification.
What am I missing?
You need code to create the NotificationChannel that will only run on Android 8.0+ devices:
NotificationManager mgr=
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O &&
mgr.getNotificationChannel(CHANNEL_WHATEVER)==null) {
mgr.createNotificationChannel(new NotificationChannel(CHANNEL_WHATEVER,
"Whatever", NotificationManager.IMPORTANCE_DEFAULT));
}
Then, for all API levels, pass in your channel identifier (here, CHANNEL_WHATEVER) to the NotificationCompat.Builder constructor. On older devices, the channel will be ignored.

Android heads-up notification not showing

I am trying to make heads-up notification work. Notification is created, but it's not displayed at the top of the app.
Here's the code responsible for building a notification:
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.arrow_up_float)
.setContentTitle("Check running time - click!")
.setContentText(String.valueOf(elapsedTime))
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH)
.setVibrate(new long[0])
.build();
The device that I'm trying to run the app is API 21. I've seen many threads, but no solution given works for me.
You need to do two things:
Make sure that your notification is properly configured. See: https://developer.android.com/guide/topics/ui/notifiers/notifications#Heads-up
AND make sure the phone is properly configured (I think this is where most get stuck).
Step 1. Configure the notification.
First, register your notification channel like so
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
NotificationChannel channel = new NotificationChannel("1", name, importance);
channel.setDescription(description);
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Then, create a notification, like so:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(textTitle)
.setContentText(textContent)
.setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE) //Important for heads-up notification
.setPriority(Notification.PRIORITY_MAX); //Important for heads-up notification
Finally, send the notifciations as you would do normally, e.g.:
Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, buildNotification);
Step 2. Configure the phone.
I noticed that I have to enable some additional settings on my phone (a Xiaomi Note 3):
Here are some ways to reach the menu:
Long press a notification, in the notification bar.
Go to: Settings > Installed apps > Select your app > Notifications
Improving on the previous step, you can help users partially by sending them to the installed apps menu, by using this intent:
startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS));
Finally, when you reach this menu enable a setting called something like "Floating notification" (the name of this setting varies between devices).
your code is almost fine. I'm using DEFAULT_VIBRATE instead of DEFAULT_ALL:
builder.setPriority(Notification.PRIORITY_HIGH);
if (Build.VERSION.SDK_INT >= 21) {
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
}
But, you can also set
builder.fullScreenIntent(sameAsContentPendingtIntent);
but ^ this one is non-deterministic. I mean that system choose to display a HeadsUp or launch Intent. In most cases it shows HeadUp, but I'm not counting on it because of Android versions, Manufacturers, launchers and so so on.
Not at last, you also need to define right Notification Channel. I think you had already done this, because you wouldn't see any notification if you don't :-) Oh lovely Android :-) Anyway, I want to say that also NotificationChannel needs to be in high priority:
channel = new NotificationChannel("uniqueId", "name", NotificationManager.IMPORTANCE_HIGH);
channel.enableVibration(true);
And also, I advise to you, check latest opinions at developer.android.com
Google is going to be more strict from now. Not only for notifications but also for 'targetApi', but that is another story, pardon me :-)
Have a nice code today
try do this :
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.arrow_up_float)
.setContentTitle("Check running time - click!")
.setContentText(String.valueOf(elapsedTime))
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH)
.setVibrate(new long[0]);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
I've encountered the same issue. The solution is simply properly setting the vibration builder.setVibration(NotificationCompat.DEFAULT_VIBRATE).
According to Google:
The notification has high priority and uses ringtones or vibrations on devices running Android 7.1 (API level 25) and lower.
I hope it helps :)
The answers provided above were correct, but are partially correct now.
For future readers, notice that
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH)
will NOT resolve the problem.
According to "Android for developers",
https://developer.android.com/guide/topics/ui/notifiers/notifications.html#Heads-up
Example conditions that might trigger heads-up notifications include the following:
The user's activity is in fullscreen mode (the app uses fullScreenIntent).
The notification has high priority and uses ringtones or vibrations on devices running Android 7.1 (API level 25) and lower.
The notification channel has high importance on devices running Android 8.0 (API level 26) and higher.
Notice that the second solution (which is mostly mentioned under this question), only works for Android 7.1 or lower.
For Android 8.0 and higher, you should create a notification channel whose importance is NotificationManager.IMPORTANCE_HIGH.
Some sample code:
NotificationChannel channel =
new NotificationChannel(
"MY_OWN_CHANNEL_ID",
"MY_OWN_CHANNEL_NAME",
NotificationManager.IMPORTANCE_HIGH);
and after that, make sure that your notification builder uses this channel to display
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(smallIcon)
.setContentTitle("Title")
.setContentText("Content")
.setChannelId("MY_OWN_CHANNEL_ID")
.setPriority(Notification.PRIORITY_HIGH)
.setVibrate(new long[0]);
Now you should be able to see heads-up notifications properly.
Just use like
NotificationManager mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent myintent = new Intent(this, MainActivity.class);
myintent.putExtra("message", msg);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
myintent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("ttile")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(1, mBuilder.build());

android show notification with a popup on top of any application

With the below code my notification are only added to the notification bar, no popup style message is displayed like if you would receive a whatsapp message when you're in another application. What makes that happen to a notification?
private void sendNotification(int distance, ViewObject viewObject) {
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notificationIntent.putExtra("path", viewObject.getPath());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(Integer.parseInt(viewObject.getRefId()), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(String.format(getString(R.string.notification), viewObject.getTitle()));
bigText.setBigContentTitle(getString(R.string.hello));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_wald_poi)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_poi))
.setColor(getResources().getColor(R.color.primary))
.setContentTitle(getString(R.string.hello))
.setContentIntent(notificationPendingIntent)
.setContentText(String.format(getString(R.string.notification), viewObject.getTitle()))
.setDefaults(Notification.DEFAULT_ALL)
.setStyle(bigText);
builder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
}
If you want use Heads-up Notifications like this:
You must change Notification priority or NotificationChannel importance.
The notification priority, set by setPriority(). The priority determines how intrusive the notification should be on Android 7.1 and lower. (For Android 8.0 and higher, you must instead set the channel importance)
On Android 7.1 (API level 25) and lower:
Set notification priority to NotificationCompat.PRIORITY_HIGH or NotificationCompat.PRIORITY_MAX.
Set ringtone and vibrations - you can use setDefaults(Notification.DEFAULT_ALL)
Android 8.0 (API level 26) and higher:
Set notification channel priority to NotificationManager.IMPORTANCE_HIGH
Notification:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_wald_poi)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_poi))
.setColor(getResources().getColor(R.color.primary))
.setContentTitle(getString(R.string.hello))
.setContentIntent(notificationPendingIntent)
.setContentText(String.format(getString(R.string.notification), viewObject.getTitle()))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setStyle(bigText)
.setPriority(NotificationCompat.PRIORITY_HIGH) // or NotificationCompat.PRIORITY_MAX
Notification channel:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel
val name = getString(R.string.notification_channel_name)
val descriptionText = getString(R.string.notification_channel_description)
val importance = NotificationManager.IMPORTANCE_HIGH
val mChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance)
mChannel.description = descriptionText
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
Important
If you'd like to further customize your channel's default notification behaviors, you can call methods such as enableLights(), setLightColor(), and setVibrationPattern() on the NotificationChannel. But remember that once you create the channel, you cannot change these settings and the user has final control of whether these behaviors are active. Other option is to uninstall and install application again.
Read more
Examples of conditions that may trigger heads-up notifications include:
The user's activity is in fullscreen mode (the app uses
fullScreenIntent).
The notification has high priority and uses
ringtones or vibrations on devices running Android 7.1 (API level 25)
and lower.
The notification channel has high importance on devices
running Android 8.0 (API level 26) and higher.
Priority:
Notification.PRIORITY_HIGH and Notification.PRIORITY_MAX was deprecated in API level 26. use NotificationCompat instead.
Here is more info :-)
You have to set the notification priority to Notification.PRIORITY_HIGH or Notification.PRIORITY_MAX. I had to also do .setDefaults(Notification.DEFAULT_ALL).
Below API level 26:
Set Notification.PRIORITY_HIGH or Notification.PRIORITY_MAX in the Builder when sending the message.
API level 26 or above:
Set channel priority high
Important:
Once the channel has a established priority it cannot be changed. If it was in LOW will not show the popup, unless you reinstall the APP.
The Android system is deciding wheter a notification is displayed as Heads-up notification. There are several conditions which may trigger a Heads-up notification:
Examples of conditions that may trigger heads-up notifications include:
The user's activity is in fullscreen mode (the app uses fullScreenIntent).
The notification has high priority and uses ringtones or vibrations on devices running Android 7.1 (API level 25) and lower.
The notification channel has high importance on devices running Android 8.0 (API level 26) and higher.
Source: https://developer.android.com/guide/topics/ui/notifiers/notifications.html#Heads-up
So if you're running Android 7.1 and lower, be sure to add a ringtone or vibration as well as the high priority. For Android 8.0 and higher, change the priority to high importance.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
// ...
.setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE)
.setPriority(NotificationCompat.PRIORITY_HIGH); // or HIGH_IMPORTANCE for Android 8.0

Categories

Resources