Jovan
Jovan

Reputation: 4794

Android bindService or/and startService

I want to create Service using bindService method. But when I close one Activity my Service is destroyed, and I don't want that.

I try to put service in foreground using startForeground(NOTIFICATION_ID, notification); service onCreate , but service still destroy.

Now I try with call two methods for starting Service at same time :

    Intent bindIntent= new Intent(this, ServiceC.class);
    startService(bindIntent);
    bindService(bindIntent, onService, BIND_AUTO_CREATE);

By calling these two methods Service not destroyed. My app work fine with this method.

Can someone explain to me whether this is a good way or if it is not can you please give me idea why startForeground(NOTIFICATION_ID, notification); does not work ?

What is the best way to use bindService but at the same time I don't want the service to self destroy.

Upvotes: 9

Views: 6782

Answers (2)

Deepscorn
Deepscorn

Reputation: 832

If you start service with startService() it is not destroyed. Tried starting a service, which extends IntentService and have a loop in onHandleIntent(). When loop is finished, then service destroyed and it is not related with Activity finish. User can close application, but service is not being killed.

public class MyService extends IntentService
{
  private static final String serviceName = "MyService ";

  public MyService () {
    super(serviceName);
  }

  @Override
  public void onDestroy()
  {
    Log.v(serviceName, "onDestroy");
    Toast.makeText(this, serviceName+" stopped", Toast.LENGTH_LONG).show();
    super.onDestroy();
  }

  @Override
  protected void onHandleIntent(Intent arg0) {

    long endTime = System.currentTimeMillis() + 30*1000;
    while (System.currentTimeMillis() < endTime) {
        synchronized (this) {
            try {
                Log.v(serviceName, "Service loop");
                wait(1000);
            } catch (Exception e) {
            }
        }
    }
  }

}

Upvotes: 0

bigstones
bigstones

Reputation: 15257

I Used the same solution and it's a legitimate one. From Service ref:

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated.

startForeground() is not working because it just tries to prevent the service from being killed by the system, but its lifecycle is another thing: if nothing is more bound to that service and it wasn't started, it just stops.

Upvotes: 8

Related Questions