Call setupNotification()
in your service's onCreate
method and clearNotification()
in your service's onDestroy
method.
private int SERVICE_NOTIFICATION = 1; // this should be unique for your app
private void setupNotification()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
Notification serviceNotification = new NotificationCompat.Builder(this)
.setContentTitle("Your Service")
.setContentText("Your Service is running in the background")
.setSmallIcon(R.drawable.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setOngoing(true)
.build();
startForeground(SERVICE_NOTIFICATION, serviceNotification);
}
else{
Notification serviceNotification = new Notification();
serviceNotification.flags = Notification.FLAG_ONGOING_EVENT;
startForeground(SERVICE_NOTIFICATION, serviceNotification);
}
}
private void clearNotification()
{
stopForeground(true);
}