How can I make a persistent notification, that will update every time the users sees it?
form the service
To show the notification when the Service is running, you call:
startForeground(R.string.notification_id, myNotification);
giving the method an ID for your service, and a Notification that you have created.
At any point, your Service can update what the user sees by using the same R.string.notification_id and posting a new Notification:
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(R.string.notification_id, myNotification);
For creating a Notification, you need to read up on Notification.Builder (android docs here).
There is also a good answer on a related question: How exactly to use Notification.Builder? Apologies for not reposting his answer, but it includes a lot of code and will sort you out.
Related
My app is coming to the foreground while app in background state when notification come but This behavior is not happening in the killed state.
This is not happening below oreo.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.drawable.tracking_app_logo)
.setContentTitle(getString(R.string.app_name))
.setContentText("Uploading database...")
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.setChannelId(CHANNEL_ID)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
startForeground(102, mBuilder.build());
What is happening is that you are creating the notification in your own activity context and never launching it from a background service, so if you don't kill the app you will be able to see the notification since the context is still alive and the notification can be created.
You should use AlarmManager to schedule your notifications, since you are using it in your own activity context, I would recommend you to read about AlarmManager service and how to get it done with notifications.
A good article on how to achieve this can be find here
http://droidmentor.com/schedule-notifications-using-alarmmanager/
How it works is basic:
First you setup a background service such as the AlarmManager to launch the notifications of your app in the background
AlarmManager will set a time to the notification and even if the app is killed it will launch your notification since AlarmManager is a service that runs in the system background.
Another tip is to use Firebase cloud messaging service combined with NotificationCompat; you just need to implement the service in your manifest like this to run notifications in background
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Check Firebase messaging documentation : https://firebase.google.com/docs/cloud-messaging/android/client
Sorry for that if you find this answer irrelevant, I posted this because I thought you are using push notification but now I think you are generating notification from with in the application let me know if I am again going in wrong direction.
You can generate notification from in the application by following ways.
Alarm Manager:
In this you can specify the time when you need the notification so when the requirement are met you can pass the Broadcast to app so that event will be triggered
eg: https://developer.android.com/reference/android/app/AlarmManager
Service:
In this you can start the sticky service that will run in the background and when the condition will met then your broadcast will get fired and you can show your notification
eg: https://developer.android.com/reference/android/app/Service
Job scheduler:
By using this you can also show the notification you want to show
eg: http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html
and if you are still facing this issue please go through this link:
https://medium.com/exploring-android/exploring-background-execution-limits-on-android-oreo-ab384762a66c
I use Onesignal to push notification and need to cancel all notification of onPause and onResume,
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager!=null)
notificationManager.cancelAll();
but it's not work correctly. When app restarted I get all old notifications. I restard my app and these old notifications need to not showing.
Please help to fix this!!
You need to use this method from OneSignal SDK clearOneSignalNotifications
or for only one notifcation cancelNotification.
Check here
I want to trigger a specific event (like ordinary vibration) when the device gets an notification from the Firebase Notifications.
All I discovered so far is that one can handle the on_click of a notification that was sent with display-messages in the background of the app.
Is it possible to let the device vibrate in the very moment the notification arrives? I would love to get the users attention to participate on my field study by answering the question sheet in the moment, the notification comes in.
Thanks alot!
There are two types of messages:
data messages (with a data property in the JSON)
notification messages (with only a notification property in the JSON)
If a notification/data message arrives while your app is active, you can handle it in onMessageReceived and do whatever you want.
If a data message arrives while your app is inactive, you can handle it in onMessageReceived and do whatever you want.
To make the phone vibrate in these cases, see the excellent example from Wizard.
If a notification message arrives while your app is inactive, it is automatically handled by the system and you can't control what happens.
Also see the documentation on message types as there are some more nuances.
Is it possible to let the device vibrate in the very moment the
notification arrives?
Yes, you can define it while generating Notification using NotificationManager class -
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true)
....
..
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
In Android, if a user sets "Show Notifications" of a specific App to off, is the notification still created? If yes, is it somehow possible to access these created but not shown notifications?
As an example, consider that to create a Status bar Notification, below code is used:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
And to POST this notification, below code is used:
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
But since the "Show Notification" is OFF, above code don't show the Notification on Status bar. So as you can see, although the NotificationCompat.Builder has CREATED a Notification object/instance and filled it with other details such as Title or Text etc. you can NOT access it as it is NOT Allowed to POST by System because of user's preference settings.
Also, Since Android 4.1, users can turn off notifications of an app from application manager, but there is NO API to acheive the same from Application code (on Non-rooted device,that is). And It is not possible to disable notifications from other apps, and you can only control notifications generated by your own app.
Few more pointers that you must have in mind:
1.As a developer we have no way to know whether a call to notify was effective or not. So if I really need to check if the notifications are disabled for the current application there is NO Such setting for that in the API.
2.You really shouldn't concern yourself with it. Just assume your notification was successful. If the user has explicitly disabled your notifications, then he/she probably had good reason to do so, and your application should not care whether the notification was displayed or not
I'm sending a C2DM update to my Android app every 1/2 hour, which creates a Notification. Problem is, when I wake up in the morning I get 15 Notifications queued up in the status bar.
How do I only keep the latest notification, overwriting previous ones?
I tried looking at the C2DM documentation (http://code.google.com/android/c2dm/) which mentions a parameter called collapse_key, but I couldn't find an explanation for how to use it, nor am I sure the solution lies on the C2DM side.
Thanks!
If you want to cancel any previous notifications that has been set on the view you can try setting one of these flags.
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_UPDATE_CURRENT
Something like this should replace your old notification i believe
NotificationManager mManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this,test.class);
Notification notification = new Notification(R.drawable.icon, "Notify", System.currentTimeMillis());
notification.setLatestEventInfo(this,"App Name","Description of the notification",
PendingIntent.getActivity(this.getBaseContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
mManager.notify(0, notification);
Notification has a property called number that shows a little number below the icon (for multiple notification). It lets you use the same Icon for Multiple Notification.
Use the same ID while updating your notification. :) Cheers.
In addition to the other answers, there is a parameter in your C2DM request that is called delay_while_idle. Make sure you are NOT including that or make it false. Your phone is "idle" when the screen is off (ie while you are sleeping). Google queues up all your messages on the server until the phone is not idle (ie when you turn on the screen in the morning). Then, Google sends all 15 messages at once and you display them at that time.
In the chrome to phone source, there is a method called sendNoRetry with this line:
if (delayWhileIdle) {
postDataBuilder.append("&")
.append(PARAM_DELAY_WHILE_IDLE).append("=1");
}
Make sure it is not true, then Google servers will send you your C2DM message every 30 minutes as expected.
collapse_id key should do the job. For updating any previous notification, just use the same key. To generate a new notification on device, use a different key.
For example,
* for chat notifications use the key "chat" (collapse_id = "chat")
* for invitations use the key "invite" (collapse_id = "invite")
So all the unqiue collapse_id notifications will group on device.
For more details visit: https://documentation.onesignal.com/reference#create-notification