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)
Related
I'm running a Handler to show some notifications in the background. While testing, when I set the delay limit to 5 seconds it works perfectly. But whenever I set it to 60 seconds or more it doesn't work. Why is that?
int delay = 1000 * 60;
HandlerThread hThread = new HandlerThread("HandlerThread");
hThread.start();
Handler handler = new Handler(hThread.getLooper());
Runnable task = new Runnable() {
#Override
public void run() {
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent launchIntent = new Intent(getApplicationContext(), AndroidLauncher.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(AndroidLauncher.this);
//Set notification information
builder.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hi!")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND)
.setContentTitle(mytitle)
.setContentText(mytext)
.setContentIntent(contentIntent);
NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(builder);
style.setSummaryText("4 Task");
style.addLine("Two");
style.addLine("Three");
style.addLine("Four");
style.addLine("Five");
Notification note = style.build();
manager.notify(50, note);
}
};
handler.postDelayed(task, delay);
Import import android.os.Handler;
and use following piece of code :
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//do your work here after 60 second
}
},60000);
There is good tutorial about Handler, HandlerThread, Looper here.
I would like to know if it is possible to send a notification in android with delay. I want that the notification message a few seconds (i.e. 5 seconds) later is received. The nofication should be created in the normal way:
Intent intent = new Intent(this, MyActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification n = new Notification.Builder(this)
.setContentTitle("Title")
.setContentText("Text")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Open", pIntent).build();
I want to avoid the approach to call Thread.sleep(5000) before sending the notification, because it blocks the App.
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
// your code
}
}, 5000);
This will run your code on the main thread after 5 seconds. If running on current thread is ok you can remove the Looper.getMainLooper().
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
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
I would like to ask which service and how to use to make reminder in android... Let's say: after 10 minutes from now show me notification in notification bar...
Thanks for your answer
Obviously you should use AlarmManager in order to setup something to be executed in given PERIOD.
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), PERIOD, pi);
where the PERIOD is your time to something that should be executed in OnAlarmReceiver.
And then, just implement method in
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager nm = (NotificationManager);
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.tickerText = "10 Minutes past";
nm.notify(0, notification);
}
Enjoy.
You should use AlarmManager. With it you can schedule an intent to be delivered. Create a BroadcastReceiver to get it and show the notification.
Somethink like this i guess, you start an runnable after 10min and open an notification in the runnable's code.
Runnable reminder = new Runnable()
{
public void run()
{
int NOTIFICATION_ID = 1324;
NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification note = new Notification(R.drawable.icon, "message", System.currentTimeMillis());
// Add and AUTO_CANCEL flag to the notification,
// this automatically removes the notification when the user presses it
note.flags |= Notification.FLAG_AUTO_CANCEL;
PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this, ActivityToOpen.class), 0);
note.setLatestEventInfo(this, "message", title, i);
notifManager.notify(NOTIFICATION_ID, note);
}
};
Handler handler = new Handler();
handler.postDelayed(reminder, 600000);