Clear app notifications in android studio - java

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);

Related

How to display a notification on the lock screen on Android

After looking at the official document of the Android studio, I created a program that alerts me according to the situation I wanted.(Actually, I just copied and pasted it.)
However, notifications only appear in the top bar now.
I'd like to have a notification window appear on the lock screen where my phone is turned off.
A notification sound is coming when the cell phone is turned off.
Do I need to design a new window in xml?
Or is there a problem?
I'm sorry if the question is weird.I look forward to your advice. Thank you.
Here is my code (Notification Method)
private void showNoti() {
builder=null;
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
manager.createNotificationChannel(
new NotificationChannel(CHANNEL_ID,CHANEL_NAME,NotificationManager.IMPORTANCE_DEFAULT)
);
builder = new NotificationCompat.Builder(this,CHANNEL_ID);
}else{
builder=new NotificationCompat.Builder(this);
}
Intent intent = new Intent(this, mapActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent fullScreenIntent = new Intent(this, mapActivity.class);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent snoozeIntent = new Intent(this,mapActivity.class);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID,0);
PendingIntent snoozePendingIntent =
PendingIntent.getBroadcast(this,0,snoozeIntent,0);
builder.setContentTitle("화재알림");
builder.setContentText("화재가 발생했습니다");
builder.setSmallIcon(R.drawable.fire);
builder.setContentIntent(pendingIntent);
builder.addAction(R.drawable.fire, getString(R.string.app_name),
snoozePendingIntent);
builder.setFullScreenIntent(fullScreenPendingIntent, true);
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
builder.setAutoCancel(true);
Notification notification = builder.build();
manager.notify(1,notification);
}

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.

Running a function after the app opens from the background after notification click

I'm pretty new to Android development. I have been able to get a notification to pop up while the app is in the background. When I click on it, it successfully loads the application backup. However I want to load an Alert from the page but only when it is opened from a notification click.
Here is the code for generating the notification. Any help would be appreciated.
private void getNotificationForPasswordChange() {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Hello";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
if (mNotificationManager != null)
mNotificationManager.createNotificationChannel(mChannel);
}
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Intent i=new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent mainIntent = PendingIntent.getActivity(this, 0,
i, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Pronto Tracker")
.setTicker("Pronto Tracker")
.setContentText("Cannot connect to server. Location is not being updated.")
.setSmallIcon(R.mipmap.ic_pronto_logo)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setOngoing(true).setContentIntent(mainIntent).
build();
mNotificationManager.notify(Constants.PASSWORD_CHANGE_NOTIFICATION_ID, notification);
}
You can pass the alert message with notification PendingIntent. Add the message or value you want to show as alert in PendingIntent .putExtra() and also specify the activity in PendingIntent where you want to show the alert in form of dialog or anything.
Intent intent = new Intent(Application.getAppContext(), MainActivity.class);
intent.putExtra("is_notification", true);
intent.putExtra("alert_message", "Hello World!");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
After that add the PendingIntent to your notification.
Second thing you need to do is to get the data from the Intent when user taps on notification.
In your MainActivity add the following code to get data from Intent:-
if (getIntent() != null) {
String message = getIntent().getStringExtra("alert_message");
boolean isNotification = getIntent().getBooleanExtra("is_notification", false);
if(is_notification){
// show alert
}
}
You should use onCreate function on your MainActivity
Add this code to parce your intent:
Intent receivedIntent = getIntent();

How do I get the program to display multiple notifications on the screen?

i cant seem to understand how to display multiple notifications without one overlaying another. In my case it only displays one at the time.
picture 1
My goal is to get it to work like on the screenshot below
picture 2
What should I change or maybe add to my code?
chunk of code assigned for notifications
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("com.example.romanchuk.appisode.notifyId", id);
intent.putExtra("com.example.romanchuk.appisode.show_id", show_id);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, sNotificationId /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(message);
bigText.setBigContentTitle(getString(R.string.app_name));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
Notification notification = null;
notification = builder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(getResources().getColor(R.color.color_accent))
.setContentTitle("Appisode")
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(inboxStyle)
.setSmallIcon(R.drawable.small_icon)
.setSound(defaultSoundUri).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(sNotificationId++, notification);
}
If you want to show multiple notifications, You Notification id should be different, If the notification id already exists in the notifications it will override that notification.
notificationManager.notify(sNotificationId++, notification);
In this sNotificationId should be different for all notification
If your id or show_id is int and not constant and if it will be different for each notification you can use that also as notification id.
Or try to give different tag for each notification like this,
notificationManager.notify(String.valueOf(System.currentTimeMillis()), sNotificationId++, notification);

Android How to show alert on another app

Hi I want to show alert after click on my notification. Here is code:
#SuppressWarnings("deprecation")
private void Notify(String notificationTitle, String notificationMessage) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon_stat, "Powiadomionko", System.currentTimeMillis());
notification.ledARGB = Color.CYAN;//0xFFff0000;
notification.ledOnMS = 800;
notification.ledOffMS = 2400;
notification.vibrate = new long[]{100, 120, 100, 120};
Intent notificationIntent = new Intent(this, TerminarzActivity.class);
notification.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_VIBRATE;
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(Serwis_updateTERM.this, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(1, notification);
}
And I want to show Alert on anything not on my Activity after click. Anyone know how to do this ?
I know i must add
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
but nothing else..
Check out the creation of this notification (taken from Geofence sample). This code creates a notification and if you touch it it launches your MainActivity.
// Create an explicit content Intent that starts the main Activity
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
// Construct a task stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the main Activity to the task stack as the parent
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions
// >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Set the notification contents
builder.setSmallIcon(R.drawable.ic_folder)
.setContentTitle(getString(R.string.geofence_transition_notification_title, transitionType, ids))
.setContentText(getString(R.string.geofence_transition_notification_text))
.setContentIntent(notificationPendingIntent);
// Get an instance of the Notification manager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
This code might help you, but still it depends what do you mean by "alert".

Categories

Resources