Creating notification when app is closed - java

I am using the onDestroy method, which I have learned is not always called when app is closed. And this has created a problem for me, where I would like to have the notification pop up every time the app closed. Is there a better way to do this? By the way, onStop and onPause are not options for me, because my app runs as a background service. Interestingly, my onDestroy method works everytime my background service is running, but whenever it is turned off, and just the app interface is open, my onDestroy never is called. This seems weird because I thought that onDestroy isn't called if the device is lacking resources, and running my service would be taking up more resources than not. Idk. Any help on this would be greatly appreciated!
`#Override
public void onDestroy(){
super.onDestroy();
Log.d("asdasd","asdasdasdasdasd");
if(notif.isChecked()) {
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("S-Dimmer")
.setContentText(getResources().getString(R.string.sDimmerStopped))
.setSmallIcon(R.drawable.ic_action_name1)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_NO_CLEAR;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, noti);
doas.isRunning = false;
}
}`

This method is not always called, so you should try from background service, as there's also some destruction process alert.
So please try to do what ever you want there in the services.
Please check out this ..
onDestroy() may or may not be called on any given activity or service. The general rule is that either onDestroy() is called, or your process is terminated, or your code crashed.
You don't. Your process may be terminated for any reason, at any time, by the user or by the OS. You may or may not be called with onDestroy() when that occurs. While you may be able to improve your success rate a little via onTaskRemoved() on a Service, this itself has proven unreliable, and it will not cover all scenarios.

you are doing it wrong way. In onDestroy method all other stuffs should implemented before super.onDestory()
try this
#Override
public void onDestroy(){
Log.d("asdasd","asdasdasdasdasd");
if(notif.isChecked()) {
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("S-Dimmer")
.setContentText(getResources().getString(R.string.sDimmerStopped))
.setSmallIcon(R.drawable.ic_action_name1)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_NO_CLEAR;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, noti);
doas.isRunning = false;
}
super.onDestroy();
}`

onTaskRemoved()
{
if(notif.isChecked()) {
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("S-Dimmer")
.setContentText(getResources().getString(R.string.sDimmerStopped))
.setSmallIcon(R.drawable.ic_action_name1)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_NO_CLEAR;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, noti);
doas.isRunning = false;
}
}

Related

Android foreground service notification not showing in status bar

I have tried various solution here on SO and can't seem to get any of them to work. The notification simply will not show. Can anyone point out where possible issues in my code could be?
private void startRunningInForeground() {
setupNotificationChannel();
Intent showTaskIntent = new Intent(getApplicationContext(), MainActivity.class);
showTaskIntent.setAction(Intent.ACTION_MAIN);
showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, SERVICE_NOTIFICATION_CHANNEL);
builder.setSmallIcon(R.drawable.ic_stat_ic_logo);
builder.setContentTitle(getString(R.string.merge_notif_title));
builder.setContentText(getString(R.string.merge_notif_description));
builder.setContentIntent(contentIntent);
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(false);
builder.setOngoing(true);
startForeground(NOTIFICATION_ID, builder.build());
}
private void setupNotificationChannel() {
// Only run this on versions of Android that require notification channels.
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return;
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(notificationManager == null) {
return;
}
NotificationChannel cachingChannel = new NotificationChannel(SERVICE_NOTIFICATION_CHANNEL,
getString(R.string.merge_channel), NotificationManager.IMPORTANCE_HIGH);
cachingChannel.setDescription(getString(R.string.merge_channel_description));
cachingChannel.enableLights(false);
cachingChannel.enableVibration(false);
notificationManager.createNotificationChannel(cachingChannel);
}
Not receiving any any error messages and the notification channel is being created because I see it in the app settings.
What does your startForeground do?
try modify this and make sure your os is > Android 8.0
btw the Channel only needs to be created once.
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
NOTIFICATION_ID, <---
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
startForeground(NOTIFICATION_ID, builder.build());
notificationManager.notify(NOTIFICATION_ID, builder.build()); <--
Maybe because of Android O bg service restrictions
//Start service:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this, YourService.class));
} else {
startService(new Intent(this, YourService.class));
}
So I was able to get it to work by extending Service instead of IntentService. I cannot give an explanation as to why this worked, but everything is now working as expected.

Clear app notifications in android studio

I have an application that sends notifications, but when the user leaves the application the notification is still there, in case he does not click on it.
So, when the user logs out, or the session user is "null", the notifications will be automatically deleted.
My code:
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void enviarNotificacao(){
Intent intent = new Intent(this, BottomNavigation.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.putExtra("totens", listaTotem);
int id = (int) (Math.random()*1000);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setTicker("Olá Marujo!!!");
builder.setContentTitle("Capitão Cupom");
builder.setContentText("Um novo tesouro próximo de você");
builder.setSmallIcon(R.drawable.logo);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo));
builder.setContentIntent(pi);
builder.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(id, builder.build());
Notification n = builder.build();
n.vibrate = new long[]{150, 300, 150, 600};
notificationManager.notify(R.drawable.logo, n);
try {
Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone toque = RingtoneManager.getRingtone(this, som);
toque.play();
}catch (Exception e){
}
Sessao.instance.setSailor(sailor);
}
NotificantionManager.cancel(id) cancels a notification with that id. NoticiationManager.cancelAll() cancels all notifications from this app. Detecting when a session ends will obviously be business logic you need to build. When it happens, call one of the 2 above functions.
Override onPause() in Activity and put this inside:
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
When leaves the application call it
notificationManager.cancel(NOTIFICATION_ID);

How can I create undeletable notifications?

this is my source code. I need, to make it undeletable - it should be delete after click on that, not by swiping in the notification manager. Is it possible?
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("NotiClick", true);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
Notification Noti;
Noti = new Notification.Builder(this)
.setContentTitle("Dont Lose It")
.setContentText("Stop monitoring by click!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, Noti);
}`
You need to use setOngoing(true) with your Notification.Builder:
Set whether this is an "ongoing" notification. Ongoing notifications cannot be dismissed by the user, so your application or service must take care of canceling them. They are typically used to indicate a background task that the user is actively engaged with (e.g., playing music) or is pending in some way and therefore occupying the device (e.g., a file download, sync operation, active network connection).

Why my regular notifications are stopped after my phone is getting off?

I wrote an app and I set an alarm manager which set to send a notification every 3 hours. Assume my notification has to be send at 11:10 and my phone is getting off at 11:00. So, I will not receive any notification. When my phone is turned on, I will receive the next notification at 2:10, so everything is working correctly.
Although, it was observed that I will not receive any notification after my phone is getting off for two round of notification. Do you have any suggestion?
The code is provided:
Intent intentAlarm = new Intent(this, NotifyBroadcast.class);
PendingIntent pintentAlarm = PendingIntent.getBroadcast(this, 0, intentAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
mgr.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), 300, pintentAlarm);
// NotifyBroadcast:
public class NotifyBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
0
);
Notification notification = new Notification(R.drawable.ic_launcher, "Let me know what is your emotion buddy!", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
notification.sound = Uri.parse("file:///sdcard/notification/notification.mp3");
//notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "emotion interface", "Let me know what is your emotion buddy!", resultPendingIntent);
int mId = 001;
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, notification);
// mNotificationManager.notify(mId,mBuilder.build());
// mNotificationManager.cancel(mId);
}
}
I didn't understand following part very well :
I will not receive any notification after my phone is getting off for two round of notification .
Just check that you are relaunching your service after reboot. For that you need to add a receiver that launches your Service again after the reboot. You need to handle that on android.intent.action.BOOT_COMPLETED intent broadcast. Some of the questions that might help you are:
Android: make notification persist across phone reboot
android notification after reboot
Android: why did the Alarm notification stop after system reboot
Hope this helps in some way.

Multiple notification on same intent

I am writing an application and in this application I need to set multiple notification with same intent just like open my application whenever user tap on any notification.
All the notification comes on different time and date without having any data but the problem is, if I set two notification for 03:27 PM and 03:28 PM then the first notification (03:27 PM) is canceled (Overwritten by second) and second is working correctly.
I am currently using this code for achieving this goal:
this method is used to set notification from Activity:
public static void setNotificationOnDateTime(Context context, long fireTime)
{
int requestID = (int) System.currentTimeMillis();
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, NotificationReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, requestID, i, 0);
am.set(AlarmManager.RTC_WAKEUP, fireTime, pi);
}
and my NotificationReceiver class look like this:
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
Log.w("TAG", "Notification fired...");
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent;
Bundle bundle = intent.getExtras().getBundle("NotificationBundle");
if(bundle == null)
{
contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, SplashScreen.class), 0);
}
else
{
contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MenuScreen.class)
.putExtra("NotificationBundle", bundle), 0);
}
Notification notif = new Notification(R.drawable.ic_launcher,
"Crazy About Android...", System.currentTimeMillis());
notif.setLatestEventInfo(context, "Me", "Message test", contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
I alerady spend a lot time on googling and found some solutions but they didn't work for me here is the link of some of them:
android pending intent notification problem
Multiple notifications to the same activity
If any one knows how to do this please help me.
Quote:
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
But you're always using 1 for the id parameter. Use a unique ID when you post several notifications.
Update If that doesn't help, you can still create Intents which do not compare as being equal, while having an equal effect.
this may be helpful
notif.flags |= Notification.FLAG_ONGOING_EVENT;
the notification will never close...
Try to set as below :
contentIntent=PendingIntent.getActivity(p_context, i, new Intent(context, MenuScreen.class),PendingIntent.FLAG_CANCEL_CURRENT);
It might help you.

Categories

Resources