I'm using a foreground service with notifications. It it's important that my notification pops up by itself and not just when you drag down the top bar.
It's working most of the time. Except on Xiaomi phones. And weirdly enough it just stopped working on a Pixel 2 API 29 as well...
I know they don't show up on older APIs if there is no sound OR vibration. Maybe it has something to do with that.
StatusNotification statusNotification = new StatusNotification(getApplicationContext());
startForeground(1, statusNotification.notification());
...
public class StatusNotification {
Context context;
long[] shortVibration;
StatusNotification(Context context){
this.context = context;
shortVibration = new long[] {0L, 100L, 0L};
// just {100L} doesn't vibrate at all
// but it has to be one short vibration and not the default one
// VibrationEffect.createOneShot() is only for Oreo and higher
createNotificationChannel();
}
void createNotificationChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager manager = context.getSystemService(NotificationManager.class);
NotificationChannel channel2 = new NotificationChannel("channel2", "Channel 2", NotificationManager.IMPORTANCE_HIGH);
channel2.setDescription("Channel 2");
channel2.enableVibration(true);
channel2.setSound(null, null);
channel2.setVibrationPattern(shortVibration);
manager.createNotificationChannel(channel2);
}
}
Notification notification(){
return new NotificationCompat.Builder(context, "channel2")
.setProgress(100,100, false)
.setContentTitle("Title")
.setColor(context.getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.ic)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setVibrate(shortVibration)
.build();
}
}
Related
Foreground service notification shows too slowly on Android 12. Used ContextCompat.startForegroundService(...) and mContext.startForegroundService(...). It still shows in 5-10 seconds.
Here is an example of my code:
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Counting steps", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableVibration(false);
channel.setSound(null, null);
channel.setShowBadge(false);
notificationManager.createNotificationChannel(channel);
}
}
The onStartCommand method:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("numberOfSteps");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification.Builder notificationBuilder = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Counting steps")
.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_directions_walk_24)
.setContentIntent(pendingIntent);
startForeground(FOREGROUND_ID, notificationBuilder.build());
}
return START_STICKY;
}
How can I start or show a foreground service notification quickly?
Services that show a notification immediately
If a foreground service has at least one of the following
characteristics, the system shows the associated notification
immediately after the service starts, even on devices that run Android
12 or higher:
The service is associated with a notification that includes action
buttons. The service has a foregroundServiceType of
mediaPlayback, mediaProjection, or phoneCall. The service
provides a use case related to phone calls, navigation, or media
playback, as defined in the notification's category
attribute. The service has opted out of the behavior
change by passing FOREGROUND_SERVICE_IMMEDIATE into
setForegroundServiceBehavior() when setting up the
notification.
On Android 13 (API level 33) or higher, if the user denies the
notification permission, they still see notices related to foreground
services in the Foreground Services (FGS) Task Manager but don't see
them in the notification drawer.
See: Services that show a notification immediately
Java example code:
Notification.Builder notificationBuilder = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Counting steps")
.setContentText(message)
.setSmallIcon(R.drawable.your_cool_icon)
.setContentIntent(pendingIntent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
notificationBuilder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
}
Kotlin example:
val notificationBuilder: Notification.Builder =
Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Notification title")
.setContentText("Content title")
.setSmallIcon(R.drawable.your_cool_icon)
.setContentIntent(pendingIntent)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
notificationBuilder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
}
I have a problem with notifications where the notification doesn't appear on my xiaomi and samsung devices but works for the other device. I've tried what people recommend like trying auto start, managing battery settings, but it still doesn't appear on both devices. I also tried to use the notify library but the results were the same. Strangely, when I checked the notification setting and then clicked on the application, it appeared as shown below
samsung
This is my notification code :
public void showNotification() {
String appname = "App Name";
String title = "Notification Title";
String text = "This is the notification text";
String iconUrl = "http://url.to.image.com/image.png";
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
TaskStackBuilder stackBuilder = TaskStackBuilder.from(MainActivity.this);
stackBuilder.addParentStack(NewsActivity.class);
stackBuilder.addNextIntent(new Intent(MainActivity.this, NewsActivity.class));
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setContentTitle(title).setContentInfo(appname).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo_wanda_flp)).setContentText(text).setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.logo_wanda_flp);
notifyManager.notify("textid", 123, builder.getNotification());
}
The code won't work on Android 8 (API 26) and above without first registering a notification channel. On Android before that, it will work just fine.
Some of the code snippets below are taken from here.
Creating a notification channel
Register notification channels inside your activity before attempting to show any notification. Alternatively, you can register them inside a custom Application class before any activities or services start (but this won't be shown here for the sake of simplicity).
#Override
public void onCreate(Bundle savedInstanceState) {
createNotificationChannel(); // Registering a notification channel
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
Deliver the notification
public void showNotification() {
// ...
// NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
// Replace with line below.
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID);
// ...
}
I'm trying to periodically run a service even when the app is killed or is in the background using workManager.
My RequestService class is given below:-
public class RequestService extends Worker {
public RequestService(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
#NonNull
#Override
public Result doWork() {
displayNotification("MY Worker", "Background work Started");
Log.i("BackJob","Running");
return Result.SUCCESS;
}
private void displayNotification(String title, String task){
NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("MyApp","My Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), "My Notifications").
setContentTitle(title).setContentText(task)
.setSmallIcon(R.mipmap.ic_launcher);
notificationManager.notify(130, notification.build());
}}
This is the main activity code:-
final PeriodicWorkRequest WorkReq = new PeriodicWorkRequest.Builder(RequestService.class,15,TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(WorkReq);
The issue is if the app is killed or is in the background then workmanager stops working.
I'm testing this on a samsung device with android version pie.
P.S :- if the app is open then i see notifications continuously after 15 mins....however as soon as i close the app.....it stops working.....and there are no more notifications
You can use foreground Service for this , Foreground Service work when app is in background.
add this method in downork method
setForegroundAsync(createForegroundInfo(progress));
Override this method in workermanager class
#NonNull
private ForegroundInfo createForegroundInfo(#NonNull String progress) {
Context context = getApplicationContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel chan = new NotificationChannel("1", "channelName", NotificationManager.IMPORTANCE_NONE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
}
Notification notification = new NotificationCompat.Builder(context, "1")
.setContentTitle("title")
.setTicker("title")
.setSmallIcon(R.drawable.ic_launcher_background)
.setOngoing(true)
.build();
return new ForegroundInfo(1,notification);
}
Now you app will work in the background.
As Per the PeriodicWorkRequest.Builder official documentation available here
The intervalMillis must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
This value is currently set to 900000 ms i.e, 15 minutes.
This is a working example that currently shows any notification regarding the version of the SO. But seemingly the problem can be related with the notify method from NotificationManagerCompat
private void makeStatusNotification(String message, Context context) {
String channelId = context.getString(R.string.worker_sync_notif_channel_id);
// Make a channel if necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel, but only on API 26+
CharSequence name = context.getString(R.string.worker_sync_notif_channel_name);
String description = context.getString(R.string.worker_sync_notif_channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
// Add the channel
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
// Create the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_cloud_upload)
.setContentTitle(context.getString(R.string.worker_sync_notif_title))
.setContentText(context.getString(R.string.worker_sync_notif_subject))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(new long[0])
.setAutoCancel(true);
// Show the notification
NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build());
}
i am trying to write a periodic workmanager script but it just run when i open the app and it just run one time (not periodic) !
here is my main activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work);
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);
NotifyWorker.pendingIntent = pendingIntent;
NotifyWorker.context = this;
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(NotifyWorker.class, 1, TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(periodicWorkRequest);
}
}
and this is my dowork method :
public Result doWork() {
Log.i("wd","wd");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context,"ctx")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher))
.setSmallIcon(R.drawable.logo)
.setContentTitle("Title")
.setContentText("Desc")
.setContentIntent(pendingIntent);
android.app.NotificationManager notificationManager =
(android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 , notificationBuilder.build());
return Result.SUCCESS;
}
why its not run every 1 minute ? what i miss ?
Per the PeriodicWorkRequest.Builder documentation:
The intervalMillis must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
That value is currently set to 900000 - i.e, 15 minutes.
First of all, you can disagree with my answer but here is the hack which I used in my project and this work very accurately without gives any problem.
It's time to see the code. One thing I pointed later and must read this point after the code. SECTION IMP
//this code in your activity, fragment or any other class
notify_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
OneTimeWorkRequest track_share_market = new OneTimeWorkRequest.Builder(NotificationWorker.class).setInitialDelay(1,TimeUnit.MINUTES).addTag("Stock_Market").build();
WorkManager.getInstance().enqueue(track_share_market);
Log.d("RishabhNotification","SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSs");
}
else {
Log.d("RishabhNotification","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
WorkManager.getInstance().cancelAllWorkByTag("Stock_Market");
}
}
});
Now your Worker class Code
public class NotificationWorker extends Worker {
public NotificationWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
#NonNull
#Override
public Result doWork() {
try {
//Some heavy operation as you want there is no need to make another thread here
//track some website for weather changes or stock market changes
//In my case doWork takes only 10sec for executing this method
ShowNotification("Market Up","Gold Price goes upto ₹25,000 ","Check the app for the new update");
StartNewRequest();
return Result.success();
} catch (Exception e) {
e.printStackTrace();
StartNewRequest();
Log.d("RishabhNotification","ERERERERERERERERERERERERERERERERERERERERERERERERERERERE");
return Result.failure();
}
}
private void StartNewRequest()
{
OneTimeWorkRequest track_market = new OneTimeWorkRequest.Builder(NotificationWorker.class).setInitialDelay(1,TimeUnit.MINUTES).addTag("Stock_Market").build();
WorkManager.getInstance().enqueue(track_market);
}
private void ShowNotification(String Message, String name, String Information)
{
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Stock Market", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setSound(null,null );
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID);
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder.setAutoCancel(false)
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE|Notification.DEFAULT_LIGHTS)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(uri)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setPriority(Notification.PRIORITY_MAX)
.setContentTitle(Message)
.setContentText(name)
.setContentInfo(Information);
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
}
}
Now Read the SECTION IMP point
This Code perfectly working in Emulator, Pixel phone, Samsung phone, Moto phone, Asus Phone, One plus phone but this same code I tested in the Xioami Devices and Huawei devices they both devices not run the code for every specific time interval(They both run the code but time may be changed) which I define in my code. I don't know why is this happen on both devices. Maybe some optimization. Check this link for more https://www.reddit.com/r/androiddev/comments/9ra0iq/workmanager_reliability_for_periodic_tasks_on/
I have not tested this code in vivo and Oppo devices.
I've been struggling with the new NotificationChannels which is introduced in API 26 and up.
I'm developing an app with an option to choose whether to be notified in four cases:
Sound and Vibrate.
Sound only.
Vibrate only.
No sound or vibrate, just a pop-up.
In all cases, my app notify with sound and vibrate whatever I choose.
My code is:
NotificationCompat.Builder builder;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new NotificationCompat.Builder(context, CHANNEL_ID);
int importance;
NotificationChannel channel;
//Boolean for choosing Sound
if(sound) {
importance = NotificationManager.IMPORTANCE_DEFAULT;
} else {
importance = NotificationManager.IMPORTANCE_LOW;
}
channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
channel.setDescription(CHANNEL_DESC);
//Boolean for choosing Vibrate
if(vibrate) {
channel.enableVibration(true);
} else {
channel.enableVibration(false);
}
notificationManager.createNotificationChannel(channel);
} else {
builder = new NotificationCompat.Builder(context);
}
if(sound && vibrate) {
//Sound and Vibrate
builder.setDefaults(Notification.DEFAULT_ALL);
} else if(sound && !vibrate) {
//Sound
builder.setDefaults(Notification.DEFAULT_SOUND);
} else if(!sound && vibrate) {
//Vibrate
builder.setDefaults(Notification.DEFAULT_VIBRATE);
} else if(!sound && !vibrate) {
//None
//Do nothing! just notification with no sound or vibration
}
builder.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setPriority(Notification.PRIORITY_MAX);
Also, I change CHANNEL_ID every time I run the app, so it gets a fresh Channel ID every time just for testing until I find a solution.
Of course, it works fine with API less than 26.
Thank you, guys!
Thank you all guys,
I managed to solve it by simply creating a NotificationCompat.Builder and NotificationChannel for each and every case, and notify each Builder when its condition is met.
I don't know if this is the best practice, but I'll try to optimize the code later, if anyone has an opinion on that feel free. But it worked so fine now.
Here's my code:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder_all, builder_sound, builder_vibrate, builder_none;
NotificationChannel channel_all = new NotificationChannel(CHANNEL_ID_ALL, CHANNEL_NAME_ALL, NotificationManager.IMPORTANCE_HIGH);
channel_all.enableVibration(true);
notificationManager.createNotificationChannel(channel_all);
NotificationChannel channel_sound = new NotificationChannel(CHANNEL_ID_SOUND, CHANNEL_NAME_SOUND, NotificationManager.IMPORTANCE_HIGH);
channel_sound.enableVibration(false);
notificationManager.createNotificationChannel(channel_sound);
NotificationChannel channel_vibrate = new NotificationChannel(CHANNEL_ID_VIBRATE, CHANNEL_NAME_VIBRATE, NotificationManager.IMPORTANCE_HIGH);
channel_vibrate.setSound(null, null);
channel_vibrate.enableVibration(true);
notificationManager.createNotificationChannel(channel_vibrate);
NotificationChannel channel_none = new NotificationChannel(CHANNEL_ID_NONE, CHANNEL_NAME_NONE, NotificationManager.IMPORTANCE_HIGH);
channel_none.setSound(null, null);
channel_none.enableVibration(false);
notificationManager.createNotificationChannel(channel_none);
//Boolean for Sound or Vibrate are chosen
if(sound && vibrate) {
builder_all = new NotificationCompat.Builder(context, CHANNEL_ID_ALL);
builder_all.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_all.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_all.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_all.build());
} else if(sound && !vibrate) {
builder_sound = new NotificationCompat.Builder(context, CHANNEL_ID_SOUND);
builder_sound.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_sound.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_sound.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_sound.build());
} else if(!sound && vibrate) {
builder_vibrate = new NotificationCompat.Builder(context, CHANNEL_ID_VIBRATE);
builder_vibrate.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_vibrate.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_vibrate.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_vibrate.build());
} else if(!sound && !vibrate) {
builder_none = new NotificationCompat.Builder(context, CHANNEL_ID_NONE);
builder_none.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_none.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_none.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_none.build());
}
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
if(sound && vibrate) {
//Sound and Vibrate
builder.setDefaults(Notification.DEFAULT_ALL);
} else if(sound && !vibrate) {
//Sound
builder.setDefaults(Notification.DEFAULT_SOUND);
} else if(!sound && vibrate) {
//Vibrate
builder.setDefaults(Notification.DEFAULT_VIBRATE);
} else if(!sound && !vibrate) {
//None
//Do nothing! just notification with no sound or vibration
}
builder.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setPriority(Notification.PRIORITY_MAX);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder.build());
}
i found this in the documentation. May be it will help you :
On Android 8.0 (API level 26) and above, importance of a notification is determined by the importance of the channel the notification was posted to. Users can change the importance of a notification channel in the system settings (figure 12). On Android 7.1 (API level 25) and below, importance of each notification is determined by the notification's priority.
And also :
Android O introduces notification channels to provide a unified system to help users manage notifications. When you target Android O, you must implement one or more notification channels to display notifications to your users. If you don't target Android O, your apps behave the same as they do on Android 7.0 when running on Android O devices.
And finally :
Individual notifications must now be put in a specific channel.
Users can now turn off notifications per channel, instead of turning off all notifications from an app.
Apps with active notifications display a notification "badge" on top of their app icon on the home/launcher screen.
Users can now snooze a notification from the drawer. You can set an automatic timeout for a notification.
Some APIs regarding notification behaviors were moved from Notification to NotificationChannel. For example, use NotificationChannel.setImportance() instead of NotificationCompat.Builder.setPriority() for Android 8.0 and higher.
If your sound and vibrate bools come from your app settings, then note that the intention is you should remove those from your app and send the user to the channel settings instead:
"After you create a notification channel, you cannot change the notification channel's visual and auditory behaviors programmatically—only the user can change the channel behaviors from the system settings. To provide your users easy access to these notification settings, you should add an item in your app's settings UI that opens these system settings."
https://developer.android.com/training/notify-user/channels#UpdateChannel