I am working on an application that uses a foreground service.
for this purpose I am calling startForeground(id,Notification)
from inside onStartCommand callback of the service.
I use a notification builder to create my notification but when I pass it to startForeground only the ticker text is displayed as i set it, everything else turns to default, i.e. the Title says " is running while i had it set to " is online"
Also anything that i had set using the setText and setInfo method in the notification.Builder does not show up instead default text like "touch for more information or to stop the application" shows in its place.
here's the relevant code:
Service :
private final int NOTIFICATION_ID=1;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"EDI: Core service Started" , Toast.LENGTH_LONG).show();
startForeground(NOTIFICATION_ID, CoreServiceNotification.getNotification(this, "EDI is online", "Online","Online and running","EDI just started"));
return super.onStartCommand(intent, flags, startId);
}
CoreServiceNotification:
public class CoreServiceNotification {
public static Notification getNotification(Context context,String title,String text,String info,String tickerText){
Notification.Builder notificationBuilder= new Notification.Builder(context);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(text);
notificationBuilder.setContentInfo(info);
notificationBuilder.setTicker(tickerText);
notificationBuilder.setLights(0x00ffff00, 1000, 0);
return notificationBuilder.build();
}
}
RESULT:
As a security feature of the Android platform, you cannot, under any circumstance, have a foregrounded service without also having a notification.
When you want to update a Notification set by startForeground(), simply build a new notication and then use NotificationManager to notify it. The key point is to use the same notification id.
To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager. notify() . To update this notification after you've issued it, update or create a NotificationCompat.
I think it's necessary to set the smallIcon first when you create the notification.
Notification.Builder notificationBuilder= new Notification.Builder(context);
notificationBuilder.setSmallIcon(R.drawable.yourIcon);
// then set other staff...
Here is another simple example from Cousera Android class, Click here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With