Search code examples
javaandroidandroid-service

Why is a service launched with both startService and bindService in Android Studio?


The following code is from the project.

In my mind, a service is launched using either startService or bindService.

But the following code use both startService and bindService, why?

public class RecordViewModel extends AndroidViewModel {

    public void connectService(Intent intent) {
        getApplication().startService(intent);
        getApplication().bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }
    
    ...
}
   

public class RecordingService extends Service {

    public class LocalBinder extends Binder {
        public RecordingService getService() {
            return RecordingService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStartCommandCalls++;
        return START_NOT_STICKY;
    }

    ...
}

Solution

  • Here is some description why startService and bindService could be used together:

    https://developer.android.com/guide/components/bound-services#bind-started-service

    It says:

    As discussed in the Services document, you can create a service that is both started and bound. That is, you can start a service by calling startService(), which allows the service to run indefinitely, and you can also allow a client to bind to the service by calling bindService().

    After that:

    Although you usually implement either onBind() or onStartCommand(), it's sometimes necessary to implement both. For example, a music player might find it useful to allow its service to run indefinitely and also provide binding. This way, an activity can start the service to play some music and the music continues to play even if the user leaves the application. Then, when the user returns to the application, the activity can bind to the service to regain control of playback.