Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Galarzaa90/5296804256f96a8d1d74d2432ce74fd2 to your computer and use it in GitHub Desktop.
Save Galarzaa90/5296804256f96a8d1d74d2432ce74fd2 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
//In a service
public void showNotification(){
Intent notificationIntent = new Intent(getApplicationContext(),MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.running_background))
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setAutoCancel(true)
.build();
startForeground(NOTIF_ID,notification);
}
//In activity
@Override
protected void onResume(){
super.onResume();
//Notification should disappear when activty goes to foreground
NotificationManager manager =
(NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(MonitorService.NOTIF_ID);
}
@Override
protected void onPause() {
super.onPause();
//Notification should appear when activity goes to background
monitorService.showNotification();
}
@Beerosagos
Copy link

Super useful, thanks!

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