Reputation: 1506
I have a forground service, started by a binding activity. When the activity forast created the service, if user initiates the service, it will make it forground by calling below code
public void makeForgroundService() {
notificationBuilder = new NotificationCompat.Builder(this);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
sessionId, new Intent(this, MainActivity.class), 0);
notificationBuilder.setContentTitle("My Test Service ")
.setContentText("Service now Running")
.setSmallIcon(R.drawable.newicon)
.setContentIntent(pendingIntent);
// notificationManager = (NotificationManager)
// getSystemService(Context.NOTIFICATION_SERVICE);
notify_id = sessionId;
Log.e(TAG,"making foreGrounf : sessionId = "+String.valueOf(notify_id));
startForeground(notify_id, notificationBuilder.build());
isForeground = true;
}
Now when activity is launched again , it is binding to the serive, (as already service is running and is forground) . Now i wanna cancel the notification, tried it on getService call, but not working !
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// Log.e(TAG, "Inside onServiceConnected");
myService = ((MyService.MyBinder) service).getService();
if(myService.isForeground){
Log.e(TAG,"From Activity,removing notification : "+myService.notify_id);
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(myService.notify_id);
}
}
I dont want to stopForground
of MyService. Just need to hide or cancel the notification.
If stopForground is the only way, will stopForground let the service liable to be killed during the activity is in foreground ? Can i set StartForground at onDestroy of activity? Is it a (right)way of doing this?
Upvotes: 1
Views: 1487
Reputation: 83
As you can see in the android services documention, you cannot have a foreground service without a notification. The point is that if a service is going to be resource intensive the user has a right to know.
Upvotes: 1
Reputation: 3776
You can send a message to your service (passing some parameter in the extras) in order to stop the foreground state.
Then in your service the only thing you need to call is to stopForeground(true)
and the notification will be removed.
Upvotes: 2