JDS
JDS

Reputation: 16998

Android - how to close notification in service started by startForeground?

Say I start a notification via the following in a service of my app:

notification = new Notification(R.drawable.icon, getText(R.string.app_name), System.currentTimeMillis());
      Intent notificationIntent = new Intent(this, mainActivity.class);
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
      initService.notification.setLatestEventInfo(this, getText(R.string.app_name), "ibike rider", pendingIntent);

      startForeground(ONGOING_NOTIFICATION, notification);

How would I go about shutting down/cancelling this service? And would it be possible to do this in another activity?

Thanks.

Upvotes: 0

Views: 2862

Answers (1)

brighteyed
brighteyed

Reputation: 146

Any "started" service (no matter if it is a background or foreground service) can be started by startService call and stopped by stopService call.

If your service can handle multiple requests in its onStartCommand implementation then you can manage its lifecycle by additional calls of startService:

public int onStartCommand(Intent intent, int flags, int startId) {
  // ...

  if (intent.getAction().equals(STOP_MY_SERVICE)) {
    stopSelf();
    return START_STICKY;
  }

  if (intent.getAction().equals(START_FOREGROUND)) {

    // startForeground(...);

    return START_STICKY;
  }

  if (intent.getAction().equals(STOP_FOREGROUND)) {
    stopForeground(true);
    return START_STICKY;
  }

  // ...
  return START_STICKY;
}

For an example see LocationService.java - GTalkSMS

Upvotes: 1

Related Questions