바인딩된 서비스 개요

바인드된 서비스란 클라이언트-서버 인터페이스 안의 서버를 말합니다. 이를 통해 활동과 같은 구성요소가 서비스에 바인딩되고, 요청을 전송하고, 응답을 수신하고, 프로세스 간 통신 (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의 기초가 되며, 그러면 클라이언트가 Message 객체를 사용하여 서비스에 명령어를 전송할 수 있게 해 주는 IBinder를 클라이언트와 공유할 수 있습니다. 또한 클라이언트가 자체적으로 Messenger를 정의하여 서비스가 메시지를 돌려보내도록 할 수 있습니다.

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

AIDL 사용
Android 인터페이스 정의 언어 (AIDL)는 객체를 운영체제가 이해할 수 있는 프리미티브로 분해하고 여러 프로세스에서 마샬링하여 IPC를 실행합니다. Messenger를 사용하는 이전 기법은 실제로 AIDL을 기본 구조로 하고 있습니다.

이전 섹션에서 언급했듯이 Messenger는 단일 스레드에 모든 클라이언트 요청의 큐를 만들므로 서비스가 한 번에 하나씩 요청을 수신합니다. 그러나 서비스가 동시에 여러 요청을 처리하게 하려면 AIDL을 직접 사용해도 됩니다. 이 경우 서비스는 스레드로부터 안전해야 하며 멀티스레딩을 할 수 있어야 합니다.

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

참고: 대부분의 애플리케이션에서 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
    }
}

Java

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 is something that might hang, then put this request
            // 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()
        }
    }
}

Java

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 is something that might hang, then put this request
            // 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
    }
}

Java

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
        }
    }
}

Java

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
    }
}

Java

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)
}

Java

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_UNBIND, BIND_NOT_FOREGROUND, 값이 없는 경우 0입니다.

추가 참고사항

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

  • 항상 DeadObjectException 예외를 트랩합니다. 이 예외는 연결이 끊어지면 발생합니다. 이 예외만 유일하게 원격 메서드에 의해 발생합니다.
  • 객체는 여러 프로세스에 걸쳐 카운트되는 참조입니다.
  • 다음 예시에 설명된 대로 클라이언트의 수명 주기를 일치시키고 해체하는 순간에 바인딩과 바인딩 해제를 짝지어야 합니다.
    • 활동이 표시되는 동안에만 서비스와 상호작용해야 한다면 onStart()에는 바인딩하고 onStop()에는 바인딩을 해제합니다.
    • 백그라운드에서 활동이 중단되어 있더라도 응답이 수신되도록 하려면 onCreate() 중에는 바인딩하고 onDestroy() 중에는 바인딩을 해제합니다. 이는 백그라운드에서 실행되는 내내 활동이 서비스를 사용해야 한다는 것을 의미하므로 서비스가 다른 프로세스에 있을 때 프로세스의 가중치가 증가하고 시스템에 의해 종료될 가능성이 높아집니다.

    참고: 활동의 onResume()onPause() 콜백에는 일반적으로 바인딩하거나 바인딩 해제하지 않습니다. 이러한 콜백은 모든 수명 주기 전환에서 발생하기 때문입니다. 이러한 전환에서 발생하는 처리를 최소한으로 유지합니다.

    또한 애플리케이션의 여러 활동이 동일한 서비스에 바인딩되고 두 활동 간에 전환이 있을 경우 현재 활동의 바인딩이 해제되면(일시중지 중에) 다음 활동이 바인딩되기 전 (재개 중)에 서비스가 소멸되고 다시 생성될 수 있습니다. 수명 주기를 조정하는 방법에 관한 이러한 활동 전환은 활동 수명 주기에 설명되어 있습니다.

서비스에 바인딩하는 방법을 보여주는 추가 샘플 코드는 ApiDemos RemoteService.java 클래스를 참고하세요.

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

서비스가 모든 클라이언트에서 바인딩 해제되면 Android 시스템이 이를 소멸시킵니다(startService()를 사용하여 시작된 경우는 예외). 따라서, 서비스가 순수하게 바인드된 서비스인 경우에는 서비스의 수명 주기를 관리할 필요가 없습니다. 클라이언트에 바인딩되었는지 여부에 따라 Android 시스템에서 이를 관리합니다.

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

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

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

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