Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active October 16, 2024 11:33
Show Gist options
  • Save kristopherjohnson/6211176 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/6211176 to your computer and use it in GitHub Desktop.
Shows a foreground notification for an Android service. Tapping the notification will display the app as if it was tapped in application launcher
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);
}
@aniketptl
Copy link

@Galarzaa90 use stopForeground(true) in onDestroy of service

@einkaaf
Copy link

einkaaf commented Jun 29, 2019

Awesome ; i was looking for this answer for 2 days !!!!

@patice31
Copy link

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));
}

@RoshanNayak12
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment