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().
Related
From android O you cant create simple background service, it has to be foreground, so I followed a tutorial and built one, but, I got this error:
Unable to start service ...SMSService#302fa17 with Intent
{ cmp=...SMSService (has extras) }: java.lang.IllegalMonitorStateException:
object not locked by thread before notify()
I saw some other topics on this, but those are all for old Notifications
Here is my code:
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification mNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Content Title")
.setContentText("Content Text")
.setSmallIcon(R.drawable.ic_check)
.setContentIntent(mPendingIntent)
.build();
startForeground(1, mNotification);
mNotification.notify();
When you try to call notify on specific object it wakes up a single thread that is waiting on this object's monitor.
Since you are not locking any thread, you don't have to use notify(). Remove mNotification.notify();.
As for displaying notification startForeground(1, notification); is enough
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.
When I receive the notification I would like it to automatically disappear and have to upload manually I, Thank you in advance.
Here I attach the code, in which I create the notification. What I want to happen is that when I receive the notification, I get off, I can see it on the screen, and after a few seconds I go up alone without having to interact with it.
public void notificacion(String label, String autor,String destino) {
NotificationCompat.Builder notifica = new
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon((((BitmapDrawable) getResources()
.getDrawable(R.drawable.ic_launcher)).getBitmap()))
.setContentTitle("tittle")
.setContentText(label)
.setAutoCancel(true);
Intent intnot = new Intent(this, MainActivity.class);
intnot.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intnot.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intnot.putExtra("Destino", destino);
PendingIntent intnotpend = PendingIntent.getActivity(this, 0, intnot, PendingIntent.FLAG_UPDATE_CURRENT);
notifica.setContentIntent(intnotpend);
notifica.setFullScreenIntent(intnotpend, true);
notifica.setContentIntent(intnotpend);
}
NotificationManager notyman = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notyman.notify(10, notifica.build());
}
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