바인드된 서비스 개요

바인드된 서비스란 클라이언트-서버 인터페이스 안의 서버를 말합니다. 이를 사용하면 구성요소(예: 활동)를 서비스에 바인딩하고, 요청을 보내고, 응답을 수신하며, 프로세스 간 통신(IPC)을 실행할 수 있습니다. 일반적으로 바인드된 서비스는 다른 애플리케이션 구성요소를 도울 때까지만 유지되고 백그라운드에서 무한히 실행되지 않습니다.

이 문서는 다른 애플리케이션 구성요소에서 서비스에 바인딩하는 방법을 포함하여 바인드된 서비스를 만드는 방법을 보여줍니다. 서비스에서 알림을 전달하는 방법이나 서비스가 포그라운드에서 실행되도록 설정하는 방법 등을 포함한 서비스 전반에 관한 자세한 내용은 서비스 문서를 참고하세요.

기본 사항

바인드된 서비스란 일종의 Service 클래스 구현으로, 이를 통해 다른 애플리케이션이 이 서비스에 바인딩하여 상호작용할 수 있도록 합니다. 서비스에 바인딩을 제공하려면 onBind() 콜백 메서드를 구현해야 합니다. 이 메서드는 클라이언트가 서비스와 상호작용하는 데 사용할 수 있는 프로그래밍 인터페이스를 정의하는 IBinder 객체를 반환합니다.

시작된 서비스에 바인딩

서비스 문서에서 설명한 바와 같이, 시작되었으면서도 바인드된 서비스를 만들 수 있습니다. 다시 말해, startService()를 호출하여 서비스를 시작하고 이를 통해 서비스가 무한히 실행되도록 할 수 있으며, bindService()를 호출하면 클라이언트가 서비스에 바인딩되도록 할 수 있다는 의미입니다.

서비스가 시작되고 바인드되도록 허용한다면, 서비스가 실제로 시작되었을 때 시스템은 클라이언트가 모두 바인딩을 해제해도 서비스를 소멸시키지 않습니다. 그 대신 서비스를 직접 확실히 중단해야 합니다. 그러려면 stopSelf() 또는 stopService()를 호출하면 됩니다.

보통은 onBind() 또는 onStartCommand()를 구현하지만, 둘 다 구현해야 할 때도 있습니다. 예를 들어 음악 플레이어의 경우 서비스를 무한히 실행하면서 바인딩도 제공하는 것이 유용할 수 있습니다. 이 경우 어떤 활동에서 서비스를 시작해 음악을 재생하면, 사용자가 애플리케이션을 닫아도 음악이 계속 재생됩니다. 그런 다음, 사용자가 애플리케이션으로 다시 돌아오면 이 활동을 서비스에 바인딩하여 재생 제어권을 다시 획득할 수 있습니다.

시작된 서비스에 바인딩을 추가할 때 서비스 수명 주기에 관한 자세한 내용은 바인드된 서비스 수명 주기 관리를 참고하세요.

클라이언트는 bindService()를 호출하여 서비스에 바인딩됩니다. 이때 서비스와의 연결을 모니터링하는 ServiceConnection의 구현을 반드시 제공해야 합니다. bindService()의 반환 값은 요청된 서비스가 존재하는지, 클라이언트에 서비스 액세스 권한이 있는지 나타냅니다. Android 시스템이 클라이언트와 서비스 사이에 연결을 생성하면 ServiceConnection에서 onServiceConnected()를 호출합니다. onServiceConnected() 메서드에는 IBinder 인수가 포함되고 클라이언트는 이를 사용하여 바인드된 서비스와 통신합니다.

여러 클라이언트를 하나의 서비스와 동시에 연결할 수 있습니다. 그러나 시스템이 IBinder 서비스 통신 채널을 캐시합니다. 다시 말해, 첫 번째 클라이언트가 바인딩될 때만 시스템이 서비스의 onBind() 메서드를 호출해 IBinder를 생성합니다. 그러면 시스템이 동일한 서비스에 바인딩되는 모든 추가 클라이언트에 동일한 IBinder를 전달합니다. onBind()는 다시 호출하지 않습니다.

마지막 클라이언트가 서비스에서 바인딩을 해제하면 시스템은 서비스를 소멸시킵니다. 단, 서비스가 startService()로 시작되었을 경우는 예외입니다.

바인드된 서비스를 구현할 때 가장 중요한 부분은 onBind() 콜백 메서드가 반환하는 인터페이스를 정의하는 것입니다. 다음 섹션에서는 서비스의 IBinder 인터페이스를 정의할 수 있는 여러 가지 다양한 방법을 설명합니다.

바인드된 서비스 생성

바인딩을 제공하는 서비스를 생성할 때는 클라이언트가 서비스와 상호작용하는 데 사용할 수 있는 프로그래밍 인터페이스를 제공하는 IBinder를 제공해야 합니다. 인터페이스를 정의하는 방법은 세 가지가 있습니다.

바인더 클래스 확장
서비스가 애플리케이션 전용이고 클라이언트와 같은 프로세스에서 실행되는 경우(이런 경우가 일반적), 인터페이스를 생성할 때 Binder 클래스를 확장하고 그 인스턴스를 onBind()에서 반환하는 방식을 사용해야 합니다. 클라이언트는 Binder를 받고, 이를 사용하여 Binder 구현이나 Service에서 제공되는 공개 메서드에 직접 액세스할 수 있습니다.

서비스가 애플리케이션을 위해 단순히 백그라운드에서 작동하는 요소에 그치는 경우 선호되는 기법입니다. 인터페이스를 생성할 때 이 방식을 사용하지 않는 경우는 서비스를 다른 애플리케이션이나 별도의 프로세스에서 사용할 때뿐입니다.

메신저 사용
인터페이스가 여러 프로세스에서 작동해야 하는 경우, Messenger로 서비스 인터페이스를 생성할 수 있습니다. 이 방식을 사용하면 서비스가 여러 가지 유형의 Message 객체에 응답하는 Handler를 정의합니다. 이 HandlerMessenger의 기초가 되어 클라이언트와 IBinder를 공유하고, 클라이언트는 Message 객체를 사용해 서비스에 명령어를 보낼 수 있게 됩니다. 그 외에도 클라이언트가 자체적으로 Messenger를 정의하여 서비스가 메시지를 돌려보내도록 할 수 있습니다.

이것이 프로세스 간 통신(IPC)을 실행하는 가장 간단한 방법입니다. Messenger가 모든 요청을 단일 스레드로 큐에 저장하므로 서비스를 스레드로부터 안전하게 설계할 필요가 없기 때문입니다.

AIDL 사용
Android 인터페이스 정의 언어(AIDL)는 객체를 운영체제가 이해할 수 있는 원시 유형으로 해체한 다음, 여러 프로세스에서 마샬링하여 IPC를 실행합니다. Messenger를 사용하는 이전 기법은 실제로 AIDL을 기본 구조로 하고 있습니다. 위에서 언급한 바와 같이 Messenger는 단일 스레드에 모든 클라이언트 요청 큐를 생성하므로 서비스는 한 번에 하나씩 요청을 수신합니다. 그러나 서비스가 동시에 여러 요청을 처리하게 하려면 AIDL을 직접 사용해도 됩니다. 이 경우에 서비스는 스레드로부터 안전해야 하고 다중 스레딩 처리가 가능해야 합니다.

AIDL을 직접 사용하려면 프로그래밍 인터페이스를 정의하는 .aidl 파일을 생성해야 합니다. Android SDK 도구는 이 파일을 사용하여 인터페이스를 구현하고 IPC를 처리하는 추상 클래스를 생성합니다. 그 후에는 개발자가 서비스 내에서 이 추상 클래스를 확장하면 됩니다.

참고: 대부분의 애플리케이션은 바인드된 서비스를 생성할 때 AIDL을 사용하면 안 됩니다. 그렇게 하면 다중 스레딩 기능이 필요할 수 있고 따라서 구현이 더욱 복잡해지기 때문입니다. 이런 이유로 AIDL은 대부분의 애플리케이션에 적합하지 않으므로 이 문서에서는 서비스에 이를 사용하는 방법에 관해서 다루지 않습니다. AIDL을 반드시 직접 사용해야 할 경우에는 AIDL 문서를 참고하세요.

바인더 클래스 확장

서비스가 로컬 애플리케이션에서만 사용되고 여러 프로세스에서 작동할 필요가 없는 경우, 자체적인 Binder 클래스를 구현하여 클라이언트가 서비스 내의 공개 메서드에 직접 액세스하도록 할 수도 있습니다.

참고: 이 방법은 클라이언트와 서비스가 같은 애플리케이션 및 프로세스에 있을 때만 통하며, 이런 경우가 가장 보편적입니다. 예를 들어 음악 애플리케이션에서 백그라운드에서 음악을 재생하는 자체 서비스에 활동을 바인딩해야 할 때 효과적입니다.

설정하는 방법은 다음과 같습니다.

  1. 서비스에서 다음 중 한 가지 기능을 하는 Binder의 인스턴스를 생성합니다.
    • 클라이언트가 호출할 수 있는 공개 메서드를 포함합니다.
    • 클라이언트가 호출할 수 있는 공개 메서드가 있는 현재 Service 인스턴스를 반환합니다.
    • 클라이언트가 호출할 수 있는 공개 메서드가 포함된 서비스가 호스팅하는 다른 클래스의 인스턴스를 반환합니다.
  2. Binder의 인스턴스를 onBind() 콜백 메서드에서 반환합니다.
  3. 클라이언트의 경우, BinderonServiceConnected() 콜백 메서드에서 받아서 제공된 메서드로 바인드된 서비스를 호출합니다.

참고: 서비스와 클라이언트가 같은 애플리케이션에 있어야 클라이언트가 반환된 객체를 전송하여 그 API를 적절히 호출할 수 있습니다. 또한 서비스와 클라이언트는 같은 프로세스에 있어야 하기도 합니다. 이 기법에서는 여러 프로세스에서 마샬링을 전혀 실행하지 않기 때문입니다.

다음 예시는 서비스가 Binder 구현을 통해 서비스 내의 메서드에 액세스할 수 있는 권한을 클라이언트에 제공하는 것을 보여줍니다.

Kotlin

class LocalService : Service() {
    // Binder given to clients
    private val binder = LocalBinder()

    // Random number generator
    private val mGenerator = Random()

    /** method for clients  */
    val randomNumber: Int
        get() = mGenerator.nextInt(100)

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    inner class LocalBinder : Binder() {
        // Return this instance of LocalService so clients can call public methods
        fun getService(): LocalService = this@LocalService
    }

    override fun onBind(intent: Intent): IBinder {
        return binder
    }
}

자바

public class LocalService extends Service {
    // Binder given to clients
    private final IBinder binder = new LocalBinder();
    // Random number generator
    private final Random mGenerator = new Random();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }

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

    /** method for clients */
    public int getRandomNumber() {
      return mGenerator.nextInt(100);
    }
}

LocalBinderLocalService의 현재 인스턴스를 검색하기 위한 getService() 메서드를 클라이언트에 제공합니다. 이렇게 하면 클라이언트가 서비스 내의 공개 메서드를 호출할 수 있습니다. 예를 들어 클라이언트는 서비스에서 getRandomNumber()를 호출할 수 있습니다.

다음은 버튼을 클릭했을 때 LocalService에 바인딩되어 getRandomNumber()를 호출하는 활동을 나타냅니다.

Kotlin

class BindingActivity : Activity() {
    private lateinit var mService: LocalService
    private var mBound: Boolean = false

    /** Defines callbacks for service binding, passed to bindService()  */
    private val connection = object : ServiceConnection {

        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            val binder = service as LocalService.LocalBinder
            mService = binder.getService()
            mBound = true
        }

        override fun onServiceDisconnected(arg0: ComponentName) {
            mBound = false
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)
    }

    override fun onStart() {
        super.onStart()
        // Bind to LocalService
        Intent(this, LocalService::class.java).also { intent ->
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onStop() {
        super.onStop()
        unbindService(connection)
        mBound = false
    }

    /** Called when a button is clicked (the button in the layout file attaches to
     * this method with the android:onClick attribute)  */
    fun onButtonClick(v: View) {
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            val num: Int = mService.randomNumber
            Toast.makeText(this, "number: $num", Toast.LENGTH_SHORT).show()
        }
    }
}

자바

public class BindingActivity extends Activity {
    LocalService mService;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(connection);
        mBound = false;
    }

    /** Called when a button is clicked (the button in the layout file attaches to
      * this method with the android:onClick attribute) */
    public void onButtonClick(View v) {
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            int num = mService.getRandomNumber();
            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
        }
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}

위 예시는 클라이언트가 ServiceConnection 구현과 onServiceConnected() 콜백을 사용하여 서비스에 바인딩되는 방법을 보여줍니다. 다음 섹션에서는 이러한 서비스에 바인딩되는 과정에 관해 자세한 정보를 제공합니다.

참고: 위의 예시에서 onStop() 메서드는 서비스에서 클라이언트의 바인딩을 해제합니다. 적절한 시기에 서비스에서 클라이언트의 바인딩을 해제해야 합니다(추가 참고사항에 설명됨).

더 많은 샘플 코드는 ApiDemosLocalService.java 클래스와 LocalServiceActivities.java 클래스를 참고하세요.

메신저 사용

서비스가 원격 프로세스와 통신해야 한다면 Messenger를 사용하여 서비스에 인터페이스를 제공할 수 있습니다. 이 기법을 사용하면 AIDL을 쓰지 않고도 프로세스 간 통신(IPC)을 실행할 수 있습니다.

인터페이스에 Messenger를 사용하는 것이 AIDL을 사용하는 것보다 더욱 간단합니다. Messenger는 모든 서비스 호출을 큐에 올리기 때문입니다. 순수한 AIDL 인터페이스는 서비스에 동시 요청을 보내고, 이를 받은 서비스는 다중 스레딩을 처리해야 합니다.

대부분의 애플리케이션에서는 서비스가 다중 스레딩을 처리할 필요가 없으므로 Messenger를 사용하면 한 번에 하나씩 호출을 처리할 수 있습니다. 서비스의 다중 스레딩 처리가 중요한 경우, AIDL을 사용하여 인터페이스를 정의해야 합니다.

다음은 Messenger 사용 방법을 간략하게 요약한 것입니다.

  1. 서비스가 각 클라이언트 호출의 콜백을 받는 Handler를 구현합니다.
  2. 그러면 서비스가 Handler를 사용하여 Messenger 객체(Handler의 참조)를 생성합니다.
  3. MessengerIBinder를 생성하고, 서비스가 이를 onBind()에서 클라이언트로 반환하도록 합니다.
  4. 클라이언트는 IBinder를 사용하여 Messenger(서비스의 Handler를 참조)를 인스턴스화하고, 이를 이용하여 Message 객체를 서비스에 전송합니다.
  5. 서비스가 각 MessageHandler로 수신합니다. 구체적으로는 handleMessage() 메서드를 사용합니다.

이렇게 하면 클라이언트가 서비스에서 호출할 메서드가 없습니다. 대신 클라이언트는 메시지(Message 객체)를 전달하여 서비스가 Handler로 받을 수 있도록 합니다.

다음은 Messenger 인터페이스를 사용하는 서비스의 간단한 예시입니다.

Kotlin

/** Command to the service to display a message  */
private const val MSG_SAY_HELLO = 1

class MessengerService : Service() {

    /**
     * Target we publish for clients to send messages to IncomingHandler.
     */
    private lateinit var mMessenger: Messenger

    /**
     * Handler of incoming messages from clients.
     */
    internal class IncomingHandler(
            context: Context,
            private val applicationContext: Context = context.applicationContext
    ) : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MSG_SAY_HELLO ->
                    Toast.makeText(applicationContext, "hello!", Toast.LENGTH_SHORT).show()
                else -> super.handleMessage(msg)
            }
        }
    }

    /**
     * When binding to the service, we return an interface to our messenger
     * for sending messages to the service.
     */
    override fun onBind(intent: Intent): IBinder? {
        Toast.makeText(applicationContext, "binding", Toast.LENGTH_SHORT).show()
        mMessenger = Messenger(IncomingHandler(this))
        return mMessenger.binder
    }
}

자바

public class MessengerService extends Service {
    /**
     * Command to the service to display a message
     */
    static final int MSG_SAY_HELLO = 1;

    /**
     * Handler of incoming messages from clients.
     */
    static class IncomingHandler extends Handler {
        private Context applicationContext;

        IncomingHandler(Context context) {
            applicationContext = context.getApplicationContext();
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SAY_HELLO:
                    Toast.makeText(applicationContext, "hello!", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    /**
     * Target we publish for clients to send messages to IncomingHandler.
     */
    Messenger mMessenger;

    /**
     * When binding to the service, we return an interface to our messenger
     * for sending messages to the service.
     */
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
        mMessenger = new Messenger(new IncomingHandler(this));
        return mMessenger.getBinder();
    }
}

참고로 HandlerhandleMessage() 메서드에서 서비스가 수신되는 Message를 받고 what 멤버에 기초하여 무엇을 할지 결정합니다.

클라이언트는 서비스가 반환한 IBinder에 기초하여 Messenger를 생성하고 send()로 메시지를 전송하기만 하면 됩니다. 예를 들어, 다음은 서비스에 바인딩되어 MSG_SAY_HELLO 메시지를 서비스에 전달하는 간단한 활동입니다.

Kotlin

class ActivityMessenger : Activity() {
    /** Messenger for communicating with the service.  */
    private var mService: Messenger? = null

    /** Flag indicating whether we have called bind on the service.  */
    private var bound: Boolean = false

    /**
     * Class for interacting with the main interface of the service.
     */
    private val mConnection = object : ServiceConnection {

        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            // This is called when the connection with the service has been
            // established, giving us the object we can use to
            // interact with the service.  We are communicating with the
            // service using a Messenger, so here we get a client-side
            // representation of that from the raw IBinder object.
            mService = Messenger(service)
            bound = true
        }

        override fun onServiceDisconnected(className: ComponentName) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null
            bound = false
        }
    }

    fun sayHello(v: View) {
        if (!bound) return
        // Create and send a message to the service, using a supported 'what' value
        val msg: Message = Message.obtain(null, MSG_SAY_HELLO, 0, 0)
        try {
            mService?.send(msg)
        } catch (e: RemoteException) {
            e.printStackTrace()
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)
    }

    override fun onStart() {
        super.onStart()
        // Bind to the service
        Intent(this, MessengerService::class.java).also { intent ->
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onStop() {
        super.onStop()
        // Unbind from the service
        if (bound) {
            unbindService(mConnection)
            bound = false
        }
    }
}

자바

public class ActivityMessenger extends Activity {
    /** Messenger for communicating with the service. */
    Messenger mService = null;

    /** Flag indicating whether we have called bind on the service. */
    boolean bound;

    /**
     * Class for interacting with the main interface of the service.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the object we can use to
            // interact with the service.  We are communicating with the
            // service using a Messenger, so here we get a client-side
            // representation of that from the raw IBinder object.
            mService = new Messenger(service);
            bound = true;
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
            bound = false;
        }
    };

    public void sayHello(View v) {
        if (!bound) return;
        // Create and send a message to the service, using a supported 'what' value
        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to the service
        bindService(new Intent(this, MessengerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (bound) {
            unbindService(mConnection);
            bound = false;
        }
    }
}

이 예시는 서비스가 클라이언트에 응답하는 방식을 보여주지 않는다는 점에 유의하세요. 서비스가 응답하게 하려면 클라이언트에서 Messenger도 생성해야 합니다. 클라이언트가 onServiceConnected() 콜백을 받으면 send() 메서드의 replyTo 매개변수에 클라이언트의 Messenger를 포함하는 서비스에 Message를 전송합니다.

양방향 메시지를 제공하는 방법의 예시는 MessengerService.java(서비스) 및 MessengerServiceActivities.java(클라이언트) 샘플을 참고하세요.

서비스에 바인딩

애플리케이션 구성요소(클라이언트)를 서비스에 바인딩하려면 bindService()를 호출하면 됩니다. 그러면 Android 시스템이 서비스의 onBind() 메서드를 호출하고, 이 메서드가 서비스와의 상호작용을 위한 IBinder를 반환합니다.

바인딩은 비동기식으로 처리되고, IBinder를 클라이언트에 반환하지 않은 상태에서 bindService()가 즉시 반환됩니다. IBinder를 수신하려면 클라이언트는 ServiceConnection의 인스턴스를 생성하고 이를 bindService()에 전달해야 합니다. ServiceConnection은 시스템이 IBinder를 전달하기 위해 호출하는 콜백 메서드를 포함합니다.

참고: 활동, 서비스, 콘텐츠 제공업체만 서비스에 바인딩할 수 있으며, broadcast receiver에서는 서비스에 바인딩할 수 없습니다.

클라이언트에서 서비스에 바인딩하려면 다음 단계를 따르세요.

  1. ServiceConnection을 구현합니다.

    이 구현으로 두 가지 콜백 메서드를 재정의해야 합니다.

    onServiceConnected()
    시스템이 이를 호출하여 서비스의 onBind() 메서드가 반환한 IBinder를 전달합니다.
    onServiceDisconnected()
    Android 시스템은 서비스로의 연결이 예기치 못하게 끊어졌을 경우(예: 서비스가 비정상 종료되었거나 중단되었을 때) 이를 호출합니다. 클라이언트가 바인딩을 해제할 때는 호출되지 않습니다.
  2. bindService()를 호출하여 ServiceConnection 구현을 전달합니다.

    참고: 메서드가 false를 반환하면 클라이언트가 서비스에 제대로 연결되지 않았다는 것을 의미합니다. 그래도 클라이언트는 unbindService()를 호출해야 합니다. 그렇지 않으면 클라이언트가 유휴 상태인 서비스를 종료하지 못하게 합니다.

  3. 시스템이 onServiceConnected() 콜백 메서드를 호출하면, 인터페이스가 정의한 메서드를 사용하여 서비스에 호출을 시작할 수 있습니다.
  4. 서비스로부터 연결을 해제하려면 unbindService()를 호출합니다.

    앱이 클라이언트를 소멸시킬 때 클라이언트가 서비스에 여전히 바인딩된 경우, 이 소멸로 인해 클라이언트가 바인딩 해제됩니다. 클라이언트가 서비스와의 상호작용을 완료하는 즉시 바인딩을 해제하는 편이 좋습니다. 이렇게 하면 유휴 상태 서비스를 종료할 수 있습니다. 바인딩 및 바인딩 해제의 적절한 시기에 관한 자세한 내용은 추가 참고사항을 확인하세요.

다음 예시에서는 위와 같이 바인더 클래스를 확장해서 생성한 서비스에 클라이언트를 연결합니다. 여기에서는 반환된 IBinderLocalBinder 클래스로 전송하고 LocalService 인스턴스를 요청하기만 하면 됩니다.

Kotlin

var mService: LocalService

val mConnection = object : ServiceConnection {
    // Called when the connection with the service is established
    override fun onServiceConnected(className: ComponentName, service: IBinder) {
        // Because we have bound to an explicit
        // service that is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.
        val binder = service as LocalService.LocalBinder
        mService = binder.getService()
        mBound = true
    }

    // Called when the connection with the service disconnects unexpectedly
    override fun onServiceDisconnected(className: ComponentName) {
        Log.e(TAG, "onServiceDisconnected")
        mBound = false
    }
}

자바

LocalService mService;
private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Because we have bound to an explicit
        // service that is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    // Called when the connection with the service disconnects unexpectedly
    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "onServiceDisconnected");
        mBound = false;
    }
};

다음 예시에서와 같이, 이 ServiceConnection이 있으면 클라이언트는 이를 bindService()에 전달하여 서비스에 바인딩할 수 있습니다.

Kotlin

Intent(this, LocalService::class.java).also { intent ->
    bindService(intent, connection, Context.BIND_AUTO_CREATE)
}

자바

Intent intent = new Intent(this, LocalService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
  • bindService()의 첫 번째 매개변수는 바인딩할 서비스의 이름을 명시적으로 지정하는 Intent입니다.

    주의: 인텐트를 사용하여 Service에 바인딩하는 경우 명시적 인텐트를 사용하여 앱이 안전한지 확인하세요. 암시적 인텐트를 사용하여 서비스를 시작하면 어떤 서비스가 인텐트에 응답할지 확신할 수 없고 어떤 서비스가 시작하는지 사용자가 알 수 없으므로 보안 위험이 있습니다. Android 5.0(API 수준 21)부터는 암시적 인텐트로 bindService()를 호출하면 시스템에서 예외가 발생합니다.

  • 두 번째 매개변수는 ServiceConnection 객체입니다.
  • 세 번째 매개변수는 바인딩 옵션을 나타내는 플래그입니다. 일반적으로는 BIND_AUTO_CREATE가 되는데, 이는 서비스가 아직 활성화되지 않았을 경우 서비스를 생성하기 위함입니다. 그 외에는 BIND_DEBUG_UNBINDBIND_NOT_FOREGROUND를 사용할 수 있고 값이 없으면 0으로 설정합니다.

추가 참고사항

다음은 서비스로의 바인딩에 관한 몇 가지 중요한 참고사항입니다.

  • 항상 DeadObjectException 예외를 트랩해야 합니다. 이 예외는 연결이 끊어지면 발생합니다. 이 예외만 유일하게 원격 메서드에 의해 발생합니다.
  • 객체는 여러 프로세스에 걸쳐 카운트되는 참조입니다.
  • 일반적으로 클라이언트의 수명 주기를 결합하고 분해하는 순간을 일치시키면서 바인딩과 바인딩 해제를 짝지어야 합니다. 이 내용은 다음 예시에서 설명합니다.
    • 활동이 표시되는 동안에만 서비스와 상호작용해야 할 경우, onStart() 중에는 바인딩하고 onStop() 중에는 바인딩을 해제해야 합니다.
    • 백그라운드에서 활동이 중단되었을 때도 응답을 받게 하고 싶을 경우, onCreate() 중에는 바인딩하고 onDestroy() 중에는 바인딩을 해제하면 됩니다. 서비스가 실행되는 내내(백그라운드에서 실행되는 시간 포함) 활동이 서비스를 사용한다는 것을 유념해야 합니다. 서비스가 다른 프로세스에 있을 경우, 사용자가 그 프로세스의 가중치를 높이면 시스템이 이를 중단할 가능성이 커집니다.

    참고: 일반적으로 활동의 onResume()onPause() 중에는 바인딩하거나 바인딩을 해제하지 말아야 합니다. 이러한 콜백은 모든 수명 주기 전환에서 발생하고 이런 전환에서 발생하는 처리는 최소한으로 유지해야 하기 때문입니다. 또한, 애플리케이션의 여러 활동이 동일한 서비스에 바인딩되었고 두 활동 사이에 전환이 있을 경우, 현재 활동의 바인딩이 해제된 후(일시중지 중) 다음 활동이 바인딩되기 전(다시 시작 중)에 서비스가 제거되었다가 다시 생성될 수 있습니다. 수명 주기를 조절하기 위한 이러한 활동 전환은 활동 문서에 설명되어 있습니다.

서비스에 바인딩하는 방법을 보여주는 더 많은 샘플 코드는 ApiDemosRemoteService.java 클래스를 참고하세요.

바인드된 서비스 수명 주기 관리

모든 클라이언트에서 서비스가 바인딩 해제되면 Android 시스템이 이를 소멸시킵니다(다만 startService() 호출과 함께 시작된 경우는 예외). 따라서 서비스가 순수하게 바인드된 서비스일 경우에는 서비스의 수명 주기를 관리하지 않아도 됩니다. 클라이언트에 바인딩되었는지 여부에 따라 Android 시스템이 대신 관리해주기 때문입니다.

그러나 onStartCommand() 콜백 메서드 구현을 선택하는 경우라면 서비스를 확실히 중지해야 합니다. 서비스가 현재 시작된 것으로 간주되기 때문입니다. 이 경우 서비스가 클라이언트에 바인딩되어 있는지 여부와 관계없이, stopSelf()를 통해 서비스가 스스로 중지되거나 다른 구성요소가 stopService()를 호출할 때까지 서비스가 실행됩니다.

또한 서비스가 시작되고 바인딩을 허용하는 경우 시스템에서 onUnbind() 메서드를 호출하면 다음 번에 클라이언트가 서비스에 바인딩될 때 onRebind() 호출을 수신하고 싶다면 true를 선택적으로 반환할 수 있습니다. onRebind()는 void를 반환하지만 클라이언트는 여전히 onServiceConnected() 콜백에서 IBinder를 수신합니다. 아래의 그림은 이런 종류의 수명 주기에 관한 로직을 보여줍니다.

그림 1. 시작되었으며 바인딩도 허용하는 서비스의 수명 주기

시작된 서비스의 수명 주기에 관한 자세한 내용은 서비스 문서를 참고하세요.