Make notification disappear after 5 minutes - android

Is it possible to make a notification automatically disappear after a period of time?

You can use the AlarmManager. I think is more appropriate and more easier to implement than an Android Service.
With AlarmManager you do not need worry about make something running until the time finish. Android do that for you, and send a brodcast when it happen. Your application must have a Receiver to get the correct intent.
Look theses examples:
Android: How to use AlarmManager
Alarm Manager Example

Now there is an option called .setTimeoutAfter(long durationMs)
https://developer.android.com/reference/android/app/Notification.Builder.html#setTimeoutAfter(long)

Yeah, you can just create a service that runs in the background that'll timeout after five minutes and delete your notification. Whether you "should" actually do that is up for debate. A notification should be there to notify the user... and the user should be able to dismiss it on their own.
From d.android.com:
A Service is an application component that can perform long-running
operations in the background and does not provide a user interface.

Yeah, it is very easy.
Where you get notification there add one handler if notification is not read by user then remove notification.
#Override
public void onMessageReceived(RemoteMessage message) {
sendNotification(message.getData().toString);
}
add notification code
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("TEST NOTIFICATION")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int id = 0;
notificationManager.notify(id, notificationBuilder.build());
removeNotification(id);
}
cancel notification code.
private void removeNotification(int id) {
Handler handler = new Handler();
long delayInMilliseconds = 20000;
handler.postDelayed(new Runnable() {
public void run() {
notificationManager.cancel(id);
}
}, delayInMilliseconds);
}

You could also use a classic Java Runnable for a simple small Thread.
Handler h = new Handler();
long delayInMilliseconds = 5000;
h.postDelayed(new Runnable() {
public void run() {
mNotificationManager.cancel(id);
}
}, delayInMilliseconds);
Also look here:
Clearing notification after a few seconds

Related

What is the difference between notificationManager.notify and startForeground in Android?

I am just curious to know what are the differences between NotificationManager.notify and startForeground in Android.
Using NotificationManager.notify you can post as many updates to a notification as you like including adjustments to progress bars via Noticiation.Builder.setProgress in this way you only show one notification to the User, and its the one required by startForeground.
When you want to update a Notification set by startForeground(), simply build a new notication and then use NotificationManager to notify it.
The KEY point is to use the same notification id.
I didn't test the scenario of repeatedly calling startForeground() to update the Notification, but I think that using NotificationManager.notify would be better.
Updating the Notification will not remove the Service from the foreground status (this can be done only by calling stopForground.
Here is an example:
private static final int notif_id=1;
#Override
public void onCreate (){
this.startForeground();
}
private void startForeground() {
startForeground(notif_id, getMyActivityNotification(""));
}
private Notification getMyActivityNotification(String text){
// The PendingIntent to launch our activity if the user selects
// this notification
CharSequence title = getText(R.string.title_activity);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);
return new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher_b3)
.setContentIntent(contentIntent).getNotification();
}
/**
* this is the method that can be called to update the Notification
*/
private void updateNotification() {
String text = "Some text that will update the notification";
Notification notification = getMyActivityNotification(text);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notif_id, notification);
}
You can find more examples and clarification on NotificationManager.notify here
I'd also suggest you to refer this page in order to understand more on startForeground
Usages of startForeground could be found here

Update Notification through Service

I am creating an app that has a constant notification that reports stats to the user. Every 10 minute, I update the stats in the app, then update the notification. The problem is, the stats update in the app, but the notification does not update until I open the app. I call the same method to update the notification regardless of if the app is open or if it is called through a service.
Is there something special I have to do because it's running through a service?
Service Code (again, this works fine):
Thread.sleep(((10 /* minutes */) * 60 * 1000));
Handler handler = new Handler(getApplicationContext().getMainLooper());
Runnable runnable = new Runnable() {
#Override
public void run() {
OverviewFragment.refresh(getApplicationContext());
}
};
handler.post(runnable);
System.out.println("Updated values through service.");
Refresh Code (for notification):
builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_white)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher_old))
.setAutoCancel(false)
.setContent(remoteViews)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_MAX);
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
builder.setOngoing(true);
notificationManager.notify(notificationId, builder.build());

Stop running handler with postdelay (Android)

I created a notification to be fired with a delay, done with Handler.postdelay
Now I want my user to be able to stop the running handler process somewhere between those 30 seconds:
handler.postDelayed(new Runnable () {
public void run() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(Inlopen.this)
.setSmallIcon(R.drawable.iconsmall)
.setContentTitle("U moet uw voeten controleren!")
.setContentText("Uw moet uw voeten controleren!");
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, mBuilder.build());
}
}, 30000 );
How to do this?
I already searched a lot, but I couldn't find out how to do it with this..
You can use Handler.removeCallbacks(Runnable). The best option would be to create a constant Runnable object and provide it when using Handler.postDelayed(Runnable, long) as you will then be able to remove said Runnable specifically from the queue.
// create the Runnable object
private final static Runnable NOTIF = new Runnable() {
#Override
public void run() {
// TODO notification code goes here...
};
};
// then use it
handler.removeCallbacks(NOTIF); // to remove any posts of NOTIF
handler.postDelayed(NOTIF, 30000); // to post NOTIF with a delay of 30 seconds
you have to call handler.removeCallbacks(null). This way all the queued runnbable will be removed

Notification for several seconds in notifications bar?

how can i create a notification in the notifications bar that disappear after 5 seconds?
For example; this is the notification code:
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
.setContentTitle("Notification")
.setContentText("This is a notification that didsappears in 5 seconds")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.addAction(R.drawable.icon)
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
Starting from this code how can i create my notification that disappear after 5 seconds?
You can simply cancel your notification after 5 seconds.For this you can use either Timer or Handler.Here is Handler solution:
Handler handler = new Handler();
long delayInMilliseconds = 5000;
handler.postDelayed(new Runnable() {
public void run() {
notificationManager.cancel(YourNotificationId);
}}, delayInMilliseconds);
if you want to use Timer instead of Handler. Then you can try:
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
notificationManager.cancel(YourNotificationId);
}},delayInMilliseconds);
}
You can use method cancel(int id) or cancelAll() to dismiss your notifications.
Start a timer for 5 seconds and when it ends call cancell();
http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)

Having trouble coding recurring notifications for Android?

I would like to send my users a notification message every 12 hours, but am having trouble figuring out where to start. Can somebody please provide a step by step guide to adding a simple notification to my users? Thanks in advance
Steps are:
Setup an Alarm via AlarmManager
On BroadcastReceiver of alarm fire populate a Notification you can then setup the next alarm in 12h
Another way is to create from the beginning recurring every 12h.
see this example AlarmManager and Notification in Android
you can use this code:
private static final int TIME = 1000*60*60*12;
new Timer().scheduleAtFixedRate(new TimerTask() {
public void run() {
showNotification();
}
}, 0, TIME);//start immediatly, run every 12hours
public void showNotification() {
final NotificationManager mNotification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final Intent launchNotifiactionIntent = new Intent(this, ActivityLauchedOnClickNotif.class);
final PendingIntent pendingIntent = PendingIntent.getActivity(this,
REQUEST_CODE, launchNotifiactionIntent,
PendingIntent.FLAG_ONE_SHOT);
Notification.Builder builder = new Notification.Builder(this)
.setWhen(System.currentTimeMillis())
.setContentTitle(titleString)
.setContentText(messageString)
.setContentIntent(pendingIntent);
mNotification.notify(NOTIFICATION_ID, builder.build());
}
this code works since API 11 ! (notification.builder)

Categories

Resources