Android local notifications not working for samsung galaxy - java

I'm struggling with complex local notifications on Android for a long time now.
I have a list of events. The user is able to choose when he/she would like to be notified:
on the same day of the event
one day before the event starts
two days before the event starts
He/she is also able to set the time when he/she wants to get notified. Every time is possible. He/she is also able to only get notified by different types of events.
What happens is, that it works fine with every device except the Samsung Galaxy Phones. Users told me that they are receiving a notification exactly one time (when they set them up) and then never again.
I tried almost everything, I'm running out of ideas. It looks like Samsung has some issues with notifications but it works for some other apps. So what's the difference between their code and mine.
Maybe someone else knows this issue and can help me out. This would be so amazing!
Here comes my code:
public int setEventNotifications(List<Event> chosenEvents) {
SharedPreferences settings = context.getSharedPreferences(Constants.PREFS_EVENT_SETTINGS, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<>();
// To cancel an existing pending intent you need to recreate the exact same and cancel it -__-
// So pending intents need to be stored in the database
deleteOldGarbagePendingIntents();
// get notification settings from shared prefs
int hours = 0;
int minutes = 0;
String time = settings.getString(Constants.PREFS_EVENT_TIME, "00:00");
String parts[] = time.split(":");
try {
hours = Integer.parseInt(parts[0]);
minutes = Integer.parseInt(parts[1]);
} catch (Exception e) {
Log.e(TAG, "Invalid time. Cannot be parsed: " + time);
}
String interval = settings.getString(Constants.PREFS_EVENT_INTERVAL, "");
String communeId = settings.getString(Constants.PREFS_EVENT_COMMUNE_ID, "");
String regionId = settings.getString(Constants.PREFS_EVENT_REGION_ID, "");
for (Event event : chosenEvents) {
// check if date is in the future
Intent intent = new Intent(context, AlarmGarbageReceiver.class);
intent.putExtra("request_code", Integer.parseInt(event.getId()));
intent.putExtra("event_type", event.getGarbageType().getType());
intent.putExtra("event_date", event.getPickupDateAsDate().getTime());
// calculate trigger time
long triggerTime = calculateTriggerTime(event.getPickupDateAsDate(), hours, minutes, interval);
Calendar alarmCalendar = Calendar.getInstance();
alarmCalendar.setTimeInMillis(triggerTime);
try {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, Integer.parseInt(event.getId()), intent, FLAG_UPDATE_CURRENT);
if (alarmManager != null) {
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), pendingIntent);
} else {
Log.e(TAG, "Alarmmanager is null");
}
intentArray.add(pendingIntent);
// save intents in database
dbHelper.insertEventData(event.getId(), event.getEventType().getType(), String.valueOf(event.getPickupDateAsDate().getTime()), event.getLocation(), event.getEventType().getColor(), communeId, regionId);
} catch (SecurityException securityException) {
Log.e(TAG, "Security Exception");
securityException.printStackTrace();
} catch (Exception exception) {
Log.e(TAG, "Exception");
exception.printStackTrace();
}
}
return intentArray.size();
}
AlarmEventReceiver class:
public class AlarmEventReceiver extends BroadcastReceiver {
private static final String NOTIFICATION_CHANNEL_NAME = "xxx_events";
private static final String NOTIFICATION_CHANNEL_ID = "xxx_events_1";
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getExtras() != null) {
Log.e(TAG, AlarmEventReceiver.class.getSimpleName() + " request code: " + intent.getExtras().getInt("request_code"));
}
int eventId = intent.getExtras().getInt("request_code");
String eventType = intent.getExtras().getString("event_type");
long pickupDate = intent.getExtras().getLong("event_date");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(pickupDate);
calendar.set(Calendar.HOUR, 6);
calendar.set(Calendar.MINUTE, 0);
long finalDate = calendar.getTimeInMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder;
Intent resultIntent = new Intent(context, EventCalendarActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(EventCalendarActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
if (notificationManager == null) {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
} else {
Log.e(TAG, "Notification Manager is NULL");
}
if (eventType != null) {
builder.setChannelId(NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle("Erinnerung")
.setContentText(eventType)
.setWhen(finalDate)
.setContentIntent(resultPendingIntent)
.setAutoCancel(false)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
}
} else {
builder = new NotificationCompat.Builder(context);
builder.setContentTitle("Erinnerung")
.setDefaults(Notification.DEFAULT_ALL)
.setContentText(eventType)
.setWhen(finalDate)
.setContentIntent(resultPendingIntent)
.setAutoCancel(false)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_DEFAULT);
}
Notification notification = builder.build();
if (notificationManager != null) {
notificationManager.notify(eventId, notification);
} else {
Log.e(TAG, "notificationManager is NULL");
}
}
}
I once had the chance to run it on a samsung phone and I think I remember there was some kind of SecurityException thrown because the phone was not able to update notifications. There was only a capacity of 500 notifications and if try to update them, old ones won't be deleted, but new ones created. You therefore reach 500 notifications quite fast and that's when the SecurityException is thrown. But I can't find the source for this anymore...

I browsed a related issue in the past, it happened on a Galaxy Note, although I'm not sure it will help.
mNotificationManager.cancel(notificationId);
mNotificationManager.notify(++notificationId, notification);
Each time a new notification has to be created, manually cancel the previous one and also update the notificationID each time.

It is working fine, tested on Samsung Galaxy s7 edge
fun showDownloadNotification() {
try {
// val selectedUri = Uri.parse(Environment.getExternalStorageState())
val notiIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
notiIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
// startActivity(intent);
val pendingIntent: PendingIntent = PendingIntent.getActivity(baseActivity, 0, notiIntent, PendingIntent.FLAG_CANCEL_CURRENT)
val builder = NotificationCompat.Builder(baseActivity, "")
.setSmallIcon(notificationIcon)
.setContentTitle("Subject Topic downloaded")
.setContentText(fileName)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(baseActivity)
// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, builder.build())
} catch (e: Exception) {
// Log.e(FragmentActivity.TAG, "Notification $e")
}
}
Might be helpful !

I also had the similar issue with Samsung devices, This is what I have done:
consider this:
builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
In the above line we have passed NOTIFICATION_CHANNEL_ID.
Now later in the code this is also added:
builder.setChannelId(NOTIFICATION_CHANNEL_ID) // don't call this method
We have already given the channel id to the builder via constructor we don't need to pass that again. remove builder.setChannelId(NOTIFICATION_CHANNEL_ID). And it will also work on samsung devices.

Related

How would I set multiple notification trigger times from one Activity?

I have a menu case that allows me to set a notification trigger based on the "term" start date. This takes user input where they select the start date for a term and creates a notification alert based on their choice:
case R.id.notify:
String startDateFromScreen = editTextStartDate.getText().toString();
String endDateFromScreen = editTextEndDate.getText().toString();
Date startDate = null;
Date endDate = null;
try {
startDate = sdf.parse(startDateFromScreen);
endDate = sdf.parse(endDateFromScreen);
} catch (ParseException e) {
e.printStackTrace();
}
Intent intent = new Intent(AddEditTermActivity.this,
MyReceiver.class);
Long triggerStartDate = startDate.getTime();
Long triggerEndDate = endDate.getTime();
intent.putExtra("start", editTextTermTitle.getText().toString() + " starts today!");
intent.putExtra("end", editTextTermTitle.getText().toString() + " ends today!");
PendingIntent startSender = PendingIntent.getBroadcast(AddEditTermActivity.this, MainActivity.termStartAlertNum++, intent, 0);
PendingIntent endSender = PendingIntent.getBroadcast(AddEditTermActivity.this, MainActivity.termEndAlertNum++, intent, 0);
AlarmManager startAlerm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
startAlerm.set(AlarmManager.RTC_WAKEUP, triggerStartDate, startSender);
return true;
I also want to be able to create a separate notification based on their selected end time, as you can see from some of the code in that section. This intent is sent to a receiver class:
public class MyReceiver extends BroadcastReceiver {
String startChannelID = "test";
static int notificationID;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, intent.getStringExtra("start"), Toast.LENGTH_LONG).show();
createNotificationChannel(context, startChannelID);
Notification start = new NotificationCompat.Builder(context, startChannelID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentText(intent.getStringExtra("start"))
.setContentTitle("Starting").build();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(notificationID++, start);
}
private void createNotificationChannel(Context context, String CHANNEL_ID) {
CharSequence name = context.getResources().getString(R.string.channel_name);
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
But when creating a separate notification/notification manager, it only shows the last notification line in the code. How can I make it so that both notifications are set on the respective dates? Time does not matter in this example.

Cloud Messaging scheduled sending does not work

Hi guys as the title suggests I have a problem regarding Firebase Cloud Messaging, everything works perfectly even when the device does not open the app for a long time, receives notifications perfectly, but the problem occurs when I schedule the daily notification via the console firebase li the first time of sending works and sends the notification to all devices, while the next day at the scheduled time the notification is no longer received and this problem I do not know how to solve it, I have tried everything without any solution, the daily notifications do not are received, can you help me thanks.
#SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class MyFirebaseMessagingService extends FirebaseMessagingService {
/*public static int NOTIFICATION_ID = 1;*/
public static String NOTIFICATION = "notification";
public static String NOTIFICATION_CHANNEL_ID = "com.fourapper.forpaper.channel";
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
generateNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
}
private void generateNotification(String body, String title) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
/*PendingIntent pendingIntent = PendingIntent.getActivities(this, 0 , new Intent[]{intent}, PendingIntent.FLAG_ONE_SHOT);*/
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
/*NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);*/
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_logo_forpapaer)
.setVibrate(new long[]{100, 500})
.setSound(soundUri)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("info")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = null;
if (intent.hasExtra(NOTIFICATION)) {
notification = intent.getParcelableExtra(NOTIFICATION);
}
int notificationId = (int) System.currentTimeMillis();
notificationManager.notify(notificationId, notification);
/*if(NOTIFICATION_ID > 2147483646){
NOTIFICATION_ID = 0;
}*/
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("Channel");
notificationChannel.setBypassDnd(true);
notificationChannel.enableLights(true);
notificationChannel.setVibrationPattern(new long[]{ 0, 500});
notificationChannel.enableVibration(true);
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(notificationId, builder.build());
}
}
below the token
public class GettingDeviceTokenService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
String deviceToken = FirebaseInstanceId.getInstance().getToken();
assert deviceToken != null;
Log.d("Device Token", deviceToken);
}
}
Below are the photos of the firebase cloud messaging console for scheduled daily sending at 12:00 AM Recipient Time Zone
sending setting change screen

Cannot enable blinking light and disable notification sound for Oreo notifications

I am working with AlarmManager, and when the alarm starts it also shows notifications. I have created notifications for Oreo and for before Oreo. Notifications before Oreo work properly - I can disable sounds and set lights, but I cannot make this work in Oreo. I had the similar issue with vibrations, but was able to find a working solution. I have tried A LOT of things (1, 2, 3, 4, 5, 6...), from NotificationCompat, to changing importance, but was unable to make it work.
My issue is only with Oreo notifications, I cannot disable sound (it goes of every time), and I cannot make light blink. I have went through a bunch of SO questions, and official documentation. Some solutions are obsolete, deprecated (NotificationCompat.Builder), others do not work at all (including some examples from the official documentation).
Here is my code for both Oreo (not working) and for older (working):
//region Oreo notifications
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "AlarmNotification";
String description = "Alarm notification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(channelIdOreo, name, importance);
mChannel.setDescription(description);
mChannel.setShowBadge(true);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
if (notificationManager != null) {
notificationManager.createNotificationChannel(mChannel);
}
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (sNotifications.equals("false")) {
//NOT WORKING
mChannel.setSound(null, null);
}
//VIBRATION WORKING
if (sVibration.equals("true")) {
if (vibrator != null && vibrator.hasVibrator()) {
VibrationEffect effect = VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE);
vibrator.vibrate(effect);
}
}
Notification notification = new Notification.Builder(context, channelIdOreo)
.setContentTitle(contentTitleText)
.setContentText(contentContentText)
.setNumber(1)
.setSmallIcon(whiteLogo)
.setBadgeIconType(whiteLogo)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build();
if (notificationManager != null) {
notificationManager.notify(notificationCode, notification);
}
}
//endregion
//region Pre-Oreo notifications
else {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(whiteLogo)
.setLargeIcon(largeIcon)
.setContentTitle(contentTitleText)
.setContentText(contentContentText)
.setOngoing(false)
.setNumber(1)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
mBuilder.setLights(colorPPDOrange, 1000, 2000);
if (sNotifications.equals("true")) {
mBuilder.setSound(uri);
}
if (sVibration.equals("true")) {
mBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
}
mBuilder.setContentIntent(pendingIntent);
if (notificationManager != null) {
notificationManager.notify(notificationCode, mBuilder.build());
}
}
//endregion
Finally found an answer. Every time I change anything related to my channel I had to have my channel id changed to a completely new id, that was NEVER used before. It cannot just be different from the current id. Other than this I replaced my string resource with actual string in code. Also I had to move a few lines of code as shown below.
This is how my code looks like now:
String channelIdOreo = "FfffffF";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//region Oreo otification
Notification notification = new Notification.Builder(context, channelIdOreo)
.setContentTitle(contentTitleText)
.setContentText(contentContentText)
.setNumber(1)
.setSmallIcon(whiteLogo)
.setBadgeIconType(whiteLogo)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build();
//endregion
NotificationChannel mChannel = new NotificationChannel(channelIdOreo, "Channel human readable title and stuff", NotificationManager.IMPORTANCE_DEFAULT);
mChannel.enableLights(true);
mChannel.setLightColor(Color.YELLOW);
//region Conditions from settings
if (sNotifications.equals("true")) {
mChannel.setSound(uri, null);
} else {
mChannel.setSound(null, null);
}
if (sVibration.equals("true")) {
mChannel.setVibrationPattern(new long[]{1000, 1000, 1000, 1000, 1000});
} else {
mChannel.enableVibration(false);
}
//endregion
if (notificationManager != null) {
notificationManager.createNotificationChannel(mChannel);
}
if (notificationManager != null) {
notificationManager.notify(notificationCode, notification);
}
}
Hope this will save some time to someone.

Repeating android heads up notifications

I am able to show heads up notifications from the service. It pop up very first notification and visible to user. But thereafter if the notification is updated then it is not popping up again as first one rather it only gives notification sound and updates it, but does not pop up again as very first.
Showing very first notification from service as below :
public class WatchMan extends Service
{
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
NotificationChannel notificationChannel;
String NOTIFICATION_CHANNEL_ID = "1";
public boolean Notif_Seven = false;
public boolean Notif_Eight = false;
public WatchMan() { }
#Override
public void onCreate()
{
try
{
mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this, null);
mBuilder.setContentTitle("App Title")
.setContentText("Up and Monitoring..")
.setTicker("Up and Monitoring..")
.setSmallIcon(R.drawable.ic_service_success)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH)
.setOnlyAlertOnce(false)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
mNotifyManager.createNotificationChannel(notificationChannel);
}
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotifyManager.notify(1, mBuilder.build());
startForeground(1, mBuilder.build());
}
catch(Exception e)
{
Log.d(TAG, "EXCEPTION IN SHOWING NOTIFICATION...\n");
Log.e(TAG, "Exception is : ", e);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// STICKY Runnable thread WHILE ( TRUE )
// my code goes here with multiple conditions checking
// Say condition 7 is false and want to notify user again.
if (!Notif_Seven)
{
Notif_Seven = true;
mBuilder.setContentText("SET DEFAULT TYPE IN SETTINGS..");
mBuilder.setTicker("SET DEFAULT TYPE IN SETTINGS..");
mNotifyManager.notify(1, mBuilder.build());
}
Thread.sleep(10000);
continue;
// Say condition 8 is false and want to notify user again.
if (!Notif_Eight)
{
Notif_Eight = true;
mBuilder.setContentText("SET PERCENTAGE SETTINGS..");
mBuilder.setTicker("SET PERCENTAGE SETTINGS..");
mNotifyManager.notify(1, mBuilder.build());
}
}
}
It showing multiple notification tickers in 4.1 one by one, But in 5.1 onwards it shows it as heads up notifications, as it should be but only very first is popping up and rest all notifications are getting updated but not popping up. I want to let user see every notification as heads up and completely visible.
Finally i have done it with startforeground call. It is working as heads up notifications above 5.1 and in below versions it is showing ticker notifications successfully.
public class WatchMan extends Service
{
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
NotificationChannel notificationChannel;
String NOTIFICATION_CHANNEL_ID = "1";
public boolean Notif_Seven = false;
public boolean Notif_Eight = false;
public WatchMan() { }
#Override
public void onCreate()
{
try
{
mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this, null);
mBuilder.setContentTitle("App Title")
.setContentText("Up and Monitoring..")
.setTicker("Up and Monitoring..")
.setSmallIcon(R.drawable.ic_service_success)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH)
.setOngoing(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
mNotifyManager.createNotificationChannel(notificationChannel);
}
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
//mNotifyManager.notify(1, mBuilder.build());
startForeground(1, mBuilder.build());
}
catch(Exception e)
{
Log.d(TAG, "EXCEPTION IN SHOWING NOTIFICATION...\n");
Log.e(TAG, "Exception is : ", e);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// STICKY Runnable thread WHILE ( TRUE )
// my code goes here with multiple conditions checking
// Say condition 7 is false and want to notify user again.
if (!Notif_Seven)
{
Notif_Seven = true;
mBuilder.setContentText("SET DEFAULT TYPE IN SETTINGS..");
mBuilder.setTicker("SET DEFAULT TYPE IN SETTINGS..");
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
startForeground(1, mBuilder.build());
}
Thread.sleep(10000);
continue;
// Say condition 8 is false and want to notify user again.
if (!Notif_Eight)
{
Notif_Eight = true;
mBuilder.setContentText("SET PERCENTAGE SETTINGS..");
mBuilder.setTicker("SET PERCENTAGE SETTINGS..");
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
startForeground(1, mBuilder.build());
}
}
}

Android java sent notification once

How do I sent the notification only once if something happens?
I got this statement:
if (diffDays <= 0 && diffHours <= 0 && diffMinutes <= 0) {
activity.sendNotificationIfTimeEnd01();
Log.d("MyApp", "I am here");
}
and this:
public void sendNotificationIfTimeEnd01() {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.google.de/?gws_rd=ssl"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_stat_notification);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
builder.setContentTitle("String one");
builder.setContentText("bla");
builder.setSubText("blabla");
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
I do get the notification if the statement is right, but if I close the app and start it I get the notification again.(Statement is still right);
Try using SharedPreferences as bleeding182 adviced you. This is a good answer on how to do that:
How to use SharedPreferences in Android to store, fetch and edit values

Categories