Forked from kristopherjohnson/showForegroundNotification.java
Last active
March 2, 2023 13:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Super useful, thanks!