-
-
Save kristopherjohnson/6211176 to your computer and use it in GitHub Desktop.
private static final int NOTIFICATION_ID = 1; | |
private void showForegroundNotification(String contentText) { | |
// Create intent that will bring our app to the front, as if it was tapped in the app | |
// launcher | |
Intent showTaskIntent = new Intent(getApplicationContext(), MyMainActivity.class); | |
showTaskIntent.setAction(Intent.ACTION_MAIN); | |
showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER); | |
showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
PendingIntent contentIntent = PendingIntent.getActivity( | |
getApplicationContext(), | |
0, | |
showTaskIntent, | |
PendingIntent.FLAG_UPDATE_CURRENT); | |
Notification notification = new Notification.Builder(getApplicationContext()) | |
.setContentTitle(getString(R.string.app_name)) | |
.setContentText(contentText) | |
.setSmallIcon(R.drawable.ic_notification) | |
.setWhen(System.currentTimeMillis()) | |
.setContentIntent(contentIntent) | |
.build(); | |
startForeground(NOTIFICATION_ID, notification); | |
} |
@martinchodev
Try using getNotification
for compatibility below API 16.
I know this gist is almost 3 years old, but I really found this useful.
However, I'm struggling to get this notification dismissed. It only closes when the application is destroyed.
What I'm trying to do is show a notification when the app goes to background (indicating that the service is still running) and when the user touches the notification (or goes back to the app from launcher/recent apps), the notification should be dismissed.
I set the notification's auto close tag to true and I'm using manager.cancel(MonitorService.NOTIF_ID)
on the activity's onResume.
Here's a code snippet:
https://gist.github.com/Galarzaa90/5296804256f96a8d1d74d2432ce74fd2
@Galarzaa90 use stopForeground(true) in onDestroy of service
Awesome ; i was looking for this answer for 2 days !!!!
Very useful, worked perfectly for 2 years, but do not work anymore with migration to API26.
I tried this : change startService to startForegroundService, but does not show notification (no error messsage).
Does anyone have an idea ?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
startForegroundService(new Intent(this, recordingService.class));
} else {
startService(new Intent(this, recordingService.class));
}
Could anyone tell me the possible reasons for foreground service to not show the notification. I have created a channel, started the service using ContextCompat.startForegroundService.
Thanks, I was truggling with this.
Any chance to extend compatibility below API version 16?