Notification is removed from status bar when I close the app - android

I send a simple notification to the user when they open the app. When I swipe the notification away from the status bar, the notification is also deleted.
I just want the notification to stay on the status bar even if I close the app like whats app Instagram and some other apps.
This is how I send notification
Context context = getActivity();
Intent intent1 = new Intent(context,MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent1, 0);
Notification.Builder builder = new Notification.Builder(context)
.setTicker("Notification")
.setContentTitle("Important Message")
.setContentText("This is an example of a push notification using a Navigation Manager")
.setSmallIcon(R.drawable.ic_add)
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
//These are necessary for the notification to pop up
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
builder.setPriority(Notification.PRIORITY_MAX);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
builder.setLights(Color.BLUE, 500, 500);
}
//after android O we must use notification channels
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Reminder to remind to review your notes",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Hello Dear friends"); //this is to test what this is
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
Notification notification = builder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
P.S1: I don't want the notification to persist like in foreground services. I just want to not go away when the app is swiped away, but the user can get rid of the notification anytime they want.
P.S2: I am not using any services, just a simple notification. Like e.g.letting the user know that they collected some badges today.

Related

Persistent notification android

I need to create a persistent notification - even on new Android versions.
I use a foreground service with (START_STICKY) to display the notification. The notification is created in the method onCreate() and from time to time I start again the foreground service - just in case it was killed.
This is how I create the notification:
String CHANNEL_ID = MainActivity.packageName+".notification";// The id of the channel.
CharSequence name = getString(R.string.app_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setSound(null, null);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, MainActivity.packageName+".notification");
Intent main = new Intent(this, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT);
// set intent so it does not start a new activity
Notification notification = nBuilder
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.icon)
.setWhen( System.currentTimeMillis())
.setContentTitle("my app")
.setContentText("my msg")
.setOngoing(true)
.setChannelId(MainActivity.packageName+".notification")
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//notificationManager.notify(StaticMembers.notifId, notification);
startForeground(StaticMembers.notifId+1, notification);
The notification is shown but on some phone models, after a few days the notification is not shown anymore, even if the service is still running.
What should I do? Is there something wrong with how I create the notification?
Should I check when the service runs if the notification is displayed and if not recreate it?
Thanks

How to show a pop-up notification when the phone is locked?

I want to show this notification as pop-up window or alert dialogue on the lock screen.
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
Map<String, String> extraData = remoteMessage.getData();
String brandID = extraData.get("brandID");
String category = extraData.get("category");
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "TAC")
.setContentText(body)
.setContentTitle(title)
.setSound(defaultSoundUri)
.setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
.setPriority(NotificationCompat.PRIORITY_HIGH) //must give priority to High, Max which will considered as heads-up notification
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_launcher_background);
Intent intent;
if(category.equals("shoes")){
intent = new Intent(this, ReceiveNotification.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
else {
intent = new Intent(this, ReceiveNotification.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
intent.putExtra("brandID", brandID);
intent.putExtra("category", category);
PendingIntent pendingIntent
= PendingIntent.getActivity(this, 10, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel notificationChannel = new NotificationChannel("TAC", "demo", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(notificationChannel);
}
int id = (int) System.currentTimeMillis();
manager.notify(id, builder.build());
}
To control the level of detail visible in the notification from the lock screen, call setVisibility() and specify one of the following values:
VISIBILITY_PUBLIC shows the notification's full content.
VISIBILITY_SECRET doesn't show any part of this notification on the lock screen.
VISIBILITY_PRIVATE shows basic information, such as the notification's icon and the content title, but hides the notification's full content.
When VISIBILITY_PRIVATE is set, you can also provide an alternate version of the notification content which hides certain details. For example, an SMS app might display a notification that shows You have 3 new text messages but hides the message contents and senders. To provide this alternative notification, first create the alternative notification with NotificationCompat.Builder as usual. Then attach the alternative notification to the normal notification with setPublicVersion().
However, the user always has final control over whether their notifications are visible on the lock screen and can even control that based on your app's notification channels.
For more detail click here

permanent notification does not show

I submitted my app at the end of 2017 in the play store and it worked.
Then it was built in Eclipse.
Now I run it in Android Studio and the same code doesn't show any notification.
It is a permanent notification which is present after I call the app's finish() method. (why I do this: see at the bottom if you want to know).
So I looked at all the examples and NONE of the work. No single notification is shown.
So I start an activity and in the activity I show the notification. Then I call finish().
This is my code:
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
intent, 0);
CharSequence connectedPart = getResources().getString(R.string.app_name);
String melding = "";
melding = getResources().getString(R.string.screentimeoutsetto) + " " + newTimeString + ".";
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this)
.setContentTitle(connectedPart)
.setTicker(connectedPart)
.setContentText(melding)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;
notificationManager.notify(2, notification);
dependencies:
dependencies{
implementation "com.android.support:support-compat:26.1.0"
}
Why I do this:
My app does 1 thing: toggle the screentimeout. So when you start it it sets the screentimeout to 30 minutes (starts, sets a notification, then finish()). Start again, it removes the notification and restore the original value for the screen timeout.
Starting with Android Oreo, all notifications require a notification channel, otherwise the notification wont post and an error will appear in your logcat. Here's an example of how you can do it, lifted from one of my apps:
private static void createNotificationChannel(Context ctx) {
if(SDK_INT < O) return;
final NotificationManager mgr = ctx.getSystemService(NotificationManager.class);
if(mgr == null) return;
final String name = ctx.getString(R.string.channel_name);
if(mgr.getNotificationChannel(name) == null) {
final NotificationChannel channel =
new NotificationChannel(CHANNEL_ID, name, IMPORTANCE_DEFAULT);
mgr.createNotificationChannel(channel);
}
}
//Usage...
createNotificationChannel(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(R.drawable.ic_alarm_white_24dp);
//etc...
manager.notify(id, builder.build());
Now from Android 8.0 and onward you need to create notification channel before showing notifications. Here is the Docs link
https://developer.android.com/training/notify-user/channels

How to make android lollipop notification dismissable on lockscreen?

On lollipop, If the user has a pin set then some notifications aren't able to be swiped away. they act like a persistent notification when attempting to be dismissed.
Some apps notifications are able to be swiped away on the lockscreen without unlocking.
I have only tested this with hide sensitive notification content, does a flag set change this ability?
How do I achieve this?
This flag makes your notification stick:
Notification.FLAG_ONGOING_EVENT;
If you leave it out you can remove it. If you put it in, it sticks.
FYI: How I make my notifications:
//These are parameters for setting up the tag in the tray
private static final String NOTIFICATION_ID_TAG="notificationID";
private static final int NOTIFICATION_ID=123456;
public void createNotification() {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, MainActivity_Host.class);
intent.putExtra(NOTIFICATION_ID_TAG, NOTIFICATION_ID);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notification
Notification noti = new Notification.Builder(this)
.setContentTitle("Service Running")
.setContentText("The service is running").setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//THIS FLAG MAKES THE NOTIFICATION STICK = YOU CAN'T SWIPE IT AWAY... IF YOU LEAVE IT OUT YOU CAN REMOVE THE NOTIFICATION
noti.flags |= Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(NOTIFICATION_ID, noti);
}
This is how you can remove the notification from within the code:
//Erase the notification that we set up when the service started
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
As you see, you can get the notification from the NotificationManager by the NOTIFICATION_ID you used to make it. This is just a number i made up.

Unable to handle Push notifications on newer Android Devices

The following is the function responsible for handling a push notification received by my app. It is supposed to redirect the user to a certain Activity in the app after he/she clicks clicks on the notification.
When I try running the app on my Android 2.3.6(API 10) device,the notifications are handled perfectly.
However,when I try running it on an AVD( Andriod 4.3 (API 18)),there is no effect- the default android logo is displayed as icon instead of ic_launcher.png, the user is not redirected to the app on click,the notification does not autohide on clicking.
Please note,that I am using if statements to check API version of the phone on which the app is installed so as to ensure that push notifications are not affected by deprecated classes.
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public static void createNotification(Context context, String payload) {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= 11) {
Intent intent = new Intent(context, tabswipe.MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification.Builder(context)
.setContentTitle("New mail from ggg")
.setContentText("zzzz")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.addAction(R.drawable.ic_launcher, "Call", pendingIntent)
.addAction(R.drawable.ic_launcher, "More", pendingIntent)
.build();
notificationManager.notify(0, n);
}
if (currentapiVersion < 11) {
Intent intent = new Intent(context, tabswipe.MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,"New Update from VIIT Perception", System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL; // Hide the notification after its selected
notification.defaults |= Notification.DEFAULT_LIGHTS; //adding LED lights to notification
notification.setLatestEventInfo(context, "Updates from VIIT Perception", payload, pendingIntent);
notificationManager.notify(0, notification);
}
}

Categories

Resources