Reputation: 301
I have an app where I'd like to show a notification at the top of the screen, with the time updating, and have it stay there until the user dismisses it or presses an action.
My question is, how do I have the notification stay at the top of the screen in that manner and is it updatable as well?
Upvotes: 4
Views: 4392
Reputation: 395
To show a sticky notification you have to setOngoing(true) when building the notification.
val builder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(description)
.setAutoCancel(false)
.setOngoing(true) <-------------
Upvotes: 1
Reputation: 4116
If you update the notification before it disappears it will stay. To do this you can send a notification with new content but the same id, then the notification will be updated and the timeout will reset.
Upvotes: 0
Reputation: 51
To make the heads-up notification stay there, you need to use
PendingIntent dummyIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
notification.setFullScreenIntent(dummyIntent, true);
My understanding from the post I got this from is that the app thinks it should keep it there until the full screen intent takes action, but it never will because it was a dummy intent.
https://stackoverflow.com/a/45516069/6296686
To update the notification use
notificationBuilder.setOnlyAlertOnce(true);
//Use the same builder when updating
notificationBuilder.setContentTitle("Updated Title");
notificationManager.notify(notificationID, notificationBuilder.build());
https://stackoverflow.com/a/15538209/6296686
Upvotes: 1
Reputation: 51
EDIT: I found an actual solution using notifications. See other answer.
I am thinking that this is done with an AlertDialog, not a notification. I personally just wanted it to be "sticky" but making an updating custom AlertDialog shouldn't be too hard. To make an AlertDialog at the top of the screen I used the following code.
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(getNotificationTitle(context, showingTasks));
dialogBuilder.setNeutralButton("Dismiss", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
//Nothing
}
});
dialogBuilder.setPositiveButton("Action", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
//Action code
}
});
Dialog dialog = dialogBuilder.create();
Window window = dialog.getWindow();
WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
windowLayoutParams.gravity = Gravity.TOP;
window.setAttributes(windowLayoutParams);
dialog.show();
https://stackoverflow.com/a/9467151/6296686
Upvotes: 0