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.
Related
problem it once notification created but other notification not create and update last notification.
I want to get new notifications
call notification method :
private void NotificationLoop() {
// one notification
G.HANDLER.postDelayed(new Runnable() {
#Override
public void run() {
populateNotification(1, "task id : " + 1, 20);
}
}, 2000);
// two notification
G.HANDLER.postDelayed(new Runnable() {
#Override
public void run() {
populateNotification(2, "task id : " + 2, 40);
}
}, 2000);
// three notification
G.HANDLER.postDelayed(new Runnable() {
#Override
public void run() {
populateNotification(3, "task id : " + 3, 80);
}
}, 3000);
}
populateNotification my method from service :
private void populateNotification(int id, String title, int percent) {
Notification notification;
Intent CancelIntent = new Intent(this, ServiceDownload.class);
CancelIntent.setAction(Constant.ACTION.CANCEL_DOANLOAD_ACTION);
CancelIntent.putExtra("ID", id);
PendingIntent CCancelIntent = PendingIntent.getService(this, 0, CancelIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setTicker(title)
.setContentText(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.setOngoing(false)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, this.getResources().getString(R.string.Cancel), CCancelIntent)
.setProgress(100, percent, false)
.setStyle((new NotificationCompat.BigTextStyle().bigText(title)))
.build();
startForeground(id, notification);
}
Foreground Service has only one notification.
So when you call startForeground(id, notification); you just replace it.
You dont have much choice to solve your problem
Create new notification, not related to service
Stop foreground service and start it again, so notification will be
exactly new but there is possibility, that user will not notice
that it is new notification and not updated old notification .
Start new Foreground Service with new notification.
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
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)
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