Android Interface Definition Language (AIDL)

A Linguagem de definição de interface do Android (AIDL) é semelhante a outras IDLs: permite que você defina a interface de programação que entre o cliente e o serviço para se comunicarem usando comunicação entre processos (IPC).

No Android, um processo normalmente não pode acessar a a memória de outro processo. Para falar, eles precisam decompor seus objetos em primitivos sistema operacional poderá entender e gerenciar os objetos através desse limite para você. O código para fazer esse gerenciamento é tedioso de escrever, então o Android faz isso para você com a AIDL.

Observação: a AIDL só será necessária se você permitir que os clientes aplicativos diferentes acessam seu serviço para IPC, e você quer lidar com o multithreading em sua serviço. Se você não precisar realizar IPC simultânea em diferentes aplicativos, crie sua interface implementando um Binder. Se você quiser realizar a IPC, mas não precisar processar várias linhas de execução, implementar a interface usando um Messenger. No entanto, certifique-se de entender os serviços vinculados antes de implementar uma AIDL.

Antes de começar a projetar a interface AIDL, lembre-se de que chamadas para uma interface AIDL são chamadas de função diretas. Não faça suposições sobre a linha de execução em que a chamada de segurança. O que acontece é diferente dependendo de a chamada ser de um thread no processo local ou remoto:

  • As chamadas feitas do processo local são executadas na mesma linha de execução que está fazendo a chamada. Se essa é a linha de execução de interface principal, que continua a ser executada na interface AIDL. Se for outra linha de execução, que é aquela que executa seu código no serviço. Assim, se apenas locais linhas de execução estejam acessando o serviço, é possível controlar totalmente quais linhas estão sendo executadas nele. Mas Se esse for o caso, não use a AIDL. crie a interface ao implementar um Binder.
  • Chamadas de um processo remoto são despachadas de um pool de linhas de execução que a plataforma mantém dentro seu próprio processo. Esteja preparado para receber chamadas de conversas desconhecidas, com várias chamadas acontecendo ao mesmo tempo. Em outras palavras, uma implementação de uma interface AIDL deve ser totalmente seguro para linhas de execução. Chamadas feitas de uma linha de execução no mesmo objeto remoto chegar em ordem no receptor.
  • A palavra-chave oneway modifica o comportamento de chamadas remotas. Quando usada, uma chamada remota e não bloquear. Ele envia os dados da transação e retorna imediatamente. A implementação da interface eventualmente recebe isso como uma chamada normal do pool de linhas de execução Binder como uma chamada remota normal. Se oneway for usado com uma chamada local, não há impacto, e a chamada ainda é síncrona.

Definição de uma interface AIDL

Defina a interface AIDL em um arquivo .aidl usando a linguagem de programação a sintaxe da linguagem de programação e salvá-la no código-fonte, no diretório src/, de ambos o aplicativo que hospeda o serviço e qualquer outro aplicativo vinculado a ele.

Ao criar cada aplicativo que contém o arquivo .aidl, as Ferramentas do SDK do Android gere uma interface IBinder com base no arquivo .aidl e salve-a em gen/ do projeto. O serviço precisa implementar a IBinder. conforme apropriado. Os aplicativos clientes poderão se vincular ao serviço e chamar métodos o IBinder para executar a IPC.

Para criar um serviço limitado usando AIDL, siga estas etapas, descritas nas seções a seguir:

  1. Criar o arquivo .aidl

    Esse arquivo define a interface de programação com assinaturas de método.

  2. Implementar a interface

    As Ferramentas do SDK do Android geram uma interface na linguagem de programação Java com base no seu .aidl. Essa interface tem uma classe abstrata interna chamada Stub que estende Binder e implementa métodos da interface AIDL. Você precisa estender o Stub e implemente os métodos.

  3. Expor a interface aos clientes

    Implemente um Service e substitua onBind() para retornar a implementação do Stub .

Cuidado: todas as alterações feitas na interface AIDL após sua primeira versão deve permanecer compatível com versões anteriores para evitar a interrupção de outros aplicativos que usam seu serviço. Isso ocorre porque o arquivo .aidl precisa ser copiado para outros aplicativos. para que eles possam acessar a interface de seu serviço, você deve manter o suporte para o interface gráfica do usuário.

Criação do arquivo .aidl

A AIDL usa uma sintaxe simples que permite declarar uma interface com um ou mais métodos que podem pegar parâmetros e retornar valores. Os parâmetros e os valores de retorno podem ser de qualquer tipo, até mesmo Interfaces geradas com AIDL.

É preciso criar o arquivo .aidl usando a linguagem de programação Java. Cada .aidl deve definir uma única interface e requer apenas a declaração e o método da interface assinaturas.

Por padrão, a AIDL suporta os seguintes tipos de dados:

  • Todos os tipos primitivos da linguagem de programação Java (como int, long, char, boolean e assim por diante)
  • Matrizes de tipos primitivos, como int[]
  • String
  • CharSequence
  • List

    Todos os elementos em List precisam ser um dos tipos de dados aceitos nesta ou uma das outras interfaces geradas com AIDL ou parcelables declarados. Um Opcionalmente, List pode ser usado como uma classe de tipo parametrizado, como: List<String>. A classe concreta real que o outro lado recebe é sempre um ArrayList, embora o é gerado para usar a interface List.

  • Map

    Todos os elementos em Map precisam ser um dos tipos de dados aceitos nesta ou uma das outras interfaces geradas com AIDL ou parcelables declarados. Os mapas de tipo parametrizado como aqueles na forma Map<String,Integer> não são compatíveis. A classe concreta real que o outro lado recebe sempre é um HashMap, embora o método seja gerado para usar a interface Map. Considere usar Uma Bundle como alternativa ao Map.

É necessário incluir uma instrução import para cada tipo adicional não listado anteriormente. mesmo que elas estejam definidas no mesmo pacote da interface.

Ao definir a interface de serviço, tenha ciência do seguinte:

  • Os métodos podem receber zero ou mais parâmetros e retornar um valor ou nulo.
  • Todos os parâmetros não primitivos exigem uma tag direcional indicando para qual caminho os dados vão: in, out ou inout (veja o exemplo abaixo).

    Primitivos, String, IBinder e gerados pela AIDL são in por padrão e não podem ser diferentes.

    Cuidado:limite a direção ao que é realmente necessários, porque o gerenciamento de parâmetros é caro.

  • Todos os comentários de código no arquivo .aidl estão no gerou IBinder exceto comentários antes da importação e do pacote declarações.
  • As constantes string e int podem ser definidas na interface AIDL, como const int VERSION = 1;.
  • As chamadas de método são despachadas por um transact() código, que normalmente se baseia em um índice de método na interface. Como este dificultar o controle de versões, pode atribuir manualmente o código da transação a um método: void method() = 10;.
  • Argumentos anuláveis e tipos de retorno precisam ser anotados usando @nullable.

Confira um exemplo de arquivo .aidl:

// IRemoteService.aidl
package com.example.android;

// Declare any non-default types here with import statements.

/** Example service interface */
interface IRemoteService {
    /** Request the process ID of this service. */
    int getPid();

    /** Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
}

Salve o arquivo .aidl no diretório src/ do projeto. Quando você criar seu aplicativo, as Ferramentas SDK geram o arquivo de interface IBinder nos diretório gen/ do projeto. O nome do arquivo gerado corresponde ao nome do arquivo .aidl, mas com uma extensão .java. Por exemplo, IRemoteService.aidl resulta em IRemoteService.java.

Se você usar o Android Studio, a compilação incremental gerará a classe binder quase imediatamente. Se você não usa o Android Studio, a ferramenta Gradle gera a classe de binder na próxima vez que você criar seu aplicativo. Crie seu projeto com o gradle assembleDebug ou gradle assembleRelease assim que você terminar de gravar o arquivo .aidl, para que seu código possa ser vinculado à classe gerada.

Implementação da interface

Quando você cria o aplicativo, as Ferramentas do SDK do Android geram um arquivo de interface .java. o nome do seu arquivo .aidl. A interface gerada inclui uma subclasse chamada Stub. que é uma implementação abstrata da interface pai, como YourInterface.Stub, e declara todos os métodos do arquivo .aidl.

Observação:Stub também define alguns métodos auxiliares, principalmente asInterface(), que usa um IBinder, geralmente aquele transmitido ao método de callback onServiceConnected() de um cliente; e retorna uma instância da interface de stub. Para mais detalhes sobre como criar essa transmissão, consulte a seção Como chamar uma IPC método.

Para implementar a interface gerada do .aidl, estenda o Binder gerado. interface de usuário, como YourInterface.Stub, e implementar os métodos herdado do arquivo .aidl.

Este é um exemplo de implementação de uma interface chamada IRemoteService, definida pelo Exemplo de IRemoteService.aidl, usando uma instância anônima:

Kotlin

private val binder = object : IRemoteService.Stub() {

    override fun getPid(): Int =
            Process.myPid()

    override fun basicTypes(
            anInt: Int,
            aLong: Long,
            aBoolean: Boolean,
            aFloat: Float,
            aDouble: Double,
            aString: String
    ) {
        // Does nothing.
    }
}

Java

private final IRemoteService.Stub binder = new IRemoteService.Stub() {
    public int getPid(){
        return Process.myPid();
    }
    public void basicTypes(int anInt, long aLong, boolean aBoolean,
        float aFloat, double aDouble, String aString) {
        // Does nothing.
    }
};

Agora, o binder é uma instância da classe Stub (um Binder). que define a interface IPC do serviço. Na próxima etapa, essa instância é exposta para para que possam interagir com o serviço.

Esteja ciente de algumas regras ao implementar a interface AIDL:

  • Não há garantia de que as chamadas recebidas sejam executadas na linha de execução principal. sobre multissegmentação desde o início e crie corretamente seu serviço para que seja seguro para linhas de execução.
  • Por padrão, as chamadas IPC são síncronas. Se você sabe que o serviço leva mais do que alguns milésimos de segundo para concluir uma solicitação, não a chame da linha de execução principal da atividade. Ele pode travar o aplicativo, fazendo com que o Android exiba a mensagem "O aplicativo não está respondendo" caixa de diálogo. Chame-o de uma linha de execução separada no cliente.
  • Somente os tipos de exceção listados na documentação de referência para Parcel.writeException() são enviadas de volta ao autor da chamada.

Exposição da interface aos clientes

Depois de implementar a interface do seu serviço, você precisa expô-la ao para que possam se associar a ele. Para expor a interface Para seu serviço, estenda Service e implemente onBind() para retornar uma instância da classe que implementa o Stub gerado, conforme discutido na seção anterior. Aqui está um exemplo serviço que expõe a interface de exemplo IRemoteService para os clientes.

Kotlin

class RemoteService : Service() {

    override fun onCreate() {
        super.onCreate()
    }

    override fun onBind(intent: Intent): IBinder {
        // Return the interface.
        return binder
    }


    private val binder = object : IRemoteService.Stub() {
        override fun getPid(): Int {
            return Process.myPid()
        }

        override fun basicTypes(
                anInt: Int,
                aLong: Long,
                aBoolean: Boolean,
                aFloat: Float,
                aDouble: Double,
                aString: String
        ) {
            // Does nothing.
        }
    }
}

Java

public class RemoteService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Return the interface.
        return binder;
    }

    private final IRemoteService.Stub binder = new IRemoteService.Stub() {
        public int getPid(){
            return Process.myPid();
        }
        public void basicTypes(int anInt, long aLong, boolean aBoolean,
            float aFloat, double aDouble, String aString) {
            // Does nothing.
        }
    };
}

Agora, quando um cliente, como uma atividade, chamar bindService() para se conectar a esse serviço, o callback onServiceConnected() do cliente receberá o Instância binder retornada pelo onBind() do serviço .

O cliente também deve ter acesso à classe de interface. Portanto, se o cliente e o serviço estão aplicativos separados, o aplicativo do cliente precisará ter uma cópia do arquivo .aidl no diretório src/, que gera o android.os.Binder interface, fornecendo ao cliente acesso aos métodos AIDL.

Quando o cliente recebe o IBinder no callback onServiceConnected(), ele precisa chamar YourServiceInterface.Stub.asInterface(service) para transmitir o para o tipo YourServiceInterface:

Kotlin

var iRemoteService: IRemoteService? = null

val mConnection = object : ServiceConnection {

    // Called when the connection with the service is established.
    override fun onServiceConnected(className: ComponentName, service: IBinder) {
        // Following the preceding example for an AIDL interface,
        // this gets an instance of the IRemoteInterface, which we can use to call on the service.
        iRemoteService = IRemoteService.Stub.asInterface(service)
    }

    // Called when the connection with the service disconnects unexpectedly.
    override fun onServiceDisconnected(className: ComponentName) {
        Log.e(TAG, "Service has unexpectedly disconnected")
        iRemoteService = null
    }
}

Java

IRemoteService iRemoteService;
private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established.
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Following the preceding example for an AIDL interface,
        // this gets an instance of the IRemoteInterface, which we can use to call on the service.
        iRemoteService = IRemoteService.Stub.asInterface(service);
    }

    // Called when the connection with the service disconnects unexpectedly.
    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "Service has unexpectedly disconnected");
        iRemoteService = null;
    }
};

Para mais exemplos de código, consulte a classe RemoteService.java em ApiDemos (link em inglês).

Passagem de objetos via IPC

No Android 10 (nível 29 da API ou mais recente), é possível definir Parcelable objeto diretamente em AIDL. Os tipos com suporte como argumentos de interface AIDL e outros parcelables também são são suportados aqui. Isso evita o trabalho adicional de escrever manualmente o código de marshalling e um . No entanto, isso também cria um struct básico. Se os acessadores personalizados ou outra funcionalidade for desejado, implemente Parcelable.

package android.graphics;

// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect {
    int left;
    int top;
    int right;
    int bottom;
}

O exemplo de código anterior gera automaticamente uma classe Java com campos inteiros left, top, right e bottom. Todo o código de marshalling relevante implementados automaticamente, e o objeto pode ser usado diretamente sem precisar adicionar implementação.

Também é possível enviar uma classe personalizada de um processo para outro usando uma interface IPC. No entanto, verifique se o código da sua turma está disponível do outro lado do canal IPC e sua classe precisa oferecer suporte à interface Parcelable. Apoio Parcelable é importante porque permite que o sistema Android decomponha objetos em primitivos que podem ser gerenciados entre processos.

Para criar uma classe personalizada compatível com Parcelable, faça o seguinte:

  1. Faça com que sua classe implemente a interface Parcelable.
  2. Implemente writeToParcel, que usa o estado atual do objeto e o grava em um Parcel.
  3. Adicione um campo estático com o nome CREATOR à classe que é um objeto de implementação a interface Parcelable.Creator.
  4. Por fim, crie um arquivo .aidl que declare a classe parcelable, conforme mostrado abaixo. arquivo Rect.aidl.

    Se você estiver usando um processo de build personalizado, não adicione o arquivo .aidl ao seu ser construído. Semelhante a um arquivo principal na linguagem C, esse arquivo .aidl não é compilado.

A AIDL usa esses métodos e campos no código gerado para gerenciar e desmembrar seus objetos.

Por exemplo, este é um arquivo Rect.aidl para criar uma classe Rect que é fracionável:

package android.graphics;

// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;

E este é um exemplo de como a classe Rect implementa o com o protocolo Parcelable.

Kotlin

import android.os.Parcel
import android.os.Parcelable

class Rect() : Parcelable {
    var left: Int = 0
    var top: Int = 0
    var right: Int = 0
    var bottom: Int = 0

    companion object CREATOR : Parcelable.Creator<Rect> {
        override fun createFromParcel(parcel: Parcel): Rect {
            return Rect(parcel)
        }

        override fun newArray(size: Int): Array<Rect?> {
            return Array(size) { null }
        }
    }

    private constructor(inParcel: Parcel) : this() {
        readFromParcel(inParcel)
    }

    override fun writeToParcel(outParcel: Parcel, flags: Int) {
        outParcel.writeInt(left)
        outParcel.writeInt(top)
        outParcel.writeInt(right)
        outParcel.writeInt(bottom)
    }

    private fun readFromParcel(inParcel: Parcel) {
        left = inParcel.readInt()
        top = inParcel.readInt()
        right = inParcel.readInt()
        bottom = inParcel.readInt()
    }

    override fun describeContents(): Int {
        return 0
    }
}

Java

import android.os.Parcel;
import android.os.Parcelable;

public final class Rect implements Parcelable {
    public int left;
    public int top;
    public int right;
    public int bottom;

    public static final Parcelable.Creator<Rect> CREATOR = new Parcelable.Creator<Rect>() {
        public Rect createFromParcel(Parcel in) {
            return new Rect(in);
        }

        public Rect[] newArray(int size) {
            return new Rect[size];
        }
    };

    public Rect() {
    }

    private Rect(Parcel in) {
        readFromParcel(in);
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(left);
        out.writeInt(top);
        out.writeInt(right);
        out.writeInt(bottom);
    }

    public void readFromParcel(Parcel in) {
        left = in.readInt();
        top = in.readInt();
        right = in.readInt();
        bottom = in.readInt();
    }

    public int describeContents() {
        return 0;
    }
}

O gerenciamento na classe Rect é simples. Dê uma olhada no outro em Parcel para conferir os outros tipos de valores que podem ser gravados para um Parcel.

Aviso: lembre-se das implicações de segurança do recebimento dados de outros processos. Nesse caso, a Rect lê quatro números da Parcel, mas cabe a você garantir que eles estejam dentro do intervalo aceitável de valores para o que o autor da chamada estiver tentando fazer. Para mais informações sobre como proteger seu aplicativo contra malware, consulte as Dicas de segurança.

Métodos com argumentos Bundle contendo Parcelables

Se um método aceita um objeto Bundle que deve conter parcelables, defina o carregador de classe de Bundle chamando Bundle.setClassLoader(ClassLoader) antes de tentar ler do Bundle. Caso contrário, o ClassNotFoundException vai aparecer, mesmo que o parcelable esteja definido corretamente no app.

Por exemplo, considere o seguinte arquivo .aidl de amostra:

// IRectInsideBundle.aidl
package com.example.android;

/** Example service interface */
interface IRectInsideBundle {
    /** Rect parcelable is stored in the bundle with key "rect". */
    void saveRect(in Bundle bundle);
}
Como mostrado na implementação abaixo, o ClassLoader é explicitamente definido no Bundle antes de ler Rect:

Kotlin

private val binder = object : IRectInsideBundle.Stub() {
    override fun saveRect(bundle: Bundle) {
      bundle.classLoader = classLoader
      val rect = bundle.getParcelable<Rect>("rect")
      process(rect) // Do more with the parcelable.
    }
}

Java

private final IRectInsideBundle.Stub binder = new IRectInsideBundle.Stub() {
    public void saveRect(Bundle bundle){
        bundle.setClassLoader(getClass().getClassLoader());
        Rect rect = bundle.getParcelable("rect");
        process(rect); // Do more with the parcelable.
    }
};

Chamada de um método IPC

Para chamar uma interface remota definida com AIDL, siga estas etapas em sua classe de chamada:

  1. Inclua o arquivo .aidl no diretório src/ do projeto.
  2. Declare uma instância da interface IBinder, que é gerada com base na AIDL.
  3. Implemente ServiceConnection.
  4. Ligue para Context.bindService(), transmitindo sua implementação de ServiceConnection.
  5. Na implementação de onServiceConnected(), você recebe uma IBinder chamada service. Ligação YourInterfaceName.Stub.asInterface((IBinder)service) a transmita o parâmetro retornado ao tipo YourInterface.
  6. Chame os métodos que definiu em sua interface. Sempre capturar Exceções DeadObjectException, que são geradas quando a conexão falhar. Além disso, capture exceções SecurityException, que são geradas quando os dois processos envolvidos na chamada do método IPC têm definições da AIDL conflitantes.
  7. Para desconectar, chame Context.unbindService() com a instância da sua interface.

Tenha em mente estes pontos ao chamar um serviço de IPC:

  • Objetos são referências contadas entre processos.
  • É possível enviar objetos anônimos como argumentos do método.

Para mais informações sobre a vinculação a um serviço, leia a Visão geral de serviços vinculados.

Aqui está um exemplo de código que demonstra a chamada de um serviço criado pela AIDL, do exemplo de Serviço remoto no projeto ApiDemos.

Kotlin

private const val BUMP_MSG = 1

class Binding : Activity() {

    /** The primary interface you call on the service.  */
    private var mService: IRemoteService? = null

    /** Another interface you use on the service.  */
    internal var secondaryService: ISecondary? = null

    private lateinit var killButton: Button
    private lateinit var callbackText: TextView
    private lateinit var handler: InternalHandler

    private var isBound: 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 is
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            mService = IRemoteService.Stub.asInterface(service)
            killButton.isEnabled = true
            callbackText.text = "Attached."

            // We want to monitor the service for as long as we are
            // connected to it.
            try {
                mService?.registerCallback(mCallback)
            } catch (e: RemoteException) {
                // In this case, the service crashes before we can
                // do anything with it. We can count on soon being
                // disconnected (and then reconnected if it can be restarted)
                // so there is no need to do anything here.
            }

            // As part of the sample, tell the user what happened.
            Toast.makeText(
                    this@Binding,
                    R.string.remote_service_connected,
                    Toast.LENGTH_SHORT
            ).show()
        }

        override fun onServiceDisconnected(className: ComponentName) {
            // This is called when the connection with the service is
            // unexpectedly disconnected&mdash;that is, its process crashed.
            mService = null
            killButton.isEnabled = false
            callbackText.text = "Disconnected."

            // As part of the sample, tell the user what happened.
            Toast.makeText(
                    this@Binding,
                    R.string.remote_service_disconnected,
                    Toast.LENGTH_SHORT
            ).show()
        }
    }

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

        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            // Connecting to a secondary interface is the same as any
            // other interface.
            secondaryService = ISecondary.Stub.asInterface(service)
            killButton.isEnabled = true
        }

        override fun onServiceDisconnected(className: ComponentName) {
            secondaryService = null
            killButton.isEnabled = false
        }
    }

    private val mBindListener = View.OnClickListener {
        // Establish a couple connections with the service, binding
        // by interface names. This lets other applications be
        // installed that replace the remote service by implementing
        // the same interface.
        val intent = Intent(this@Binding, RemoteService::class.java)
        intent.action = IRemoteService::class.java.name
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
        intent.action = ISecondary::class.java.name
        bindService(intent, secondaryConnection, Context.BIND_AUTO_CREATE)
        isBound = true
        callbackText.text = "Binding."
    }

    private val unbindListener = View.OnClickListener {
        if (isBound) {
            // If we have received the service, and hence registered with
            // it, then now is the time to unregister.
            try {
                mService?.unregisterCallback(mCallback)
            } catch (e: RemoteException) {
                // There is nothing special we need to do if the service
                // crashes.
            }

            // Detach our existing connection.
            unbindService(mConnection)
            unbindService(secondaryConnection)
            killButton.isEnabled = false
            isBound = false
            callbackText.text = "Unbinding."
        }
    }

    private val killListener = View.OnClickListener {
        // To kill the process hosting the service, we need to know its
        // PID.  Conveniently, the service has a call that returns
        // that information.
        try {
            secondaryService?.pid?.also { pid ->
                // Note that, though this API lets us request to
                // kill any process based on its PID, the kernel
                // still imposes standard restrictions on which PIDs you
                // can actually kill. Typically this means only
                // the process running your application and any additional
                // processes created by that app, as shown here. Packages
                // sharing a common UID are also able to kill each
                // other's processes.
                Process.killProcess(pid)
                callbackText.text = "Killed service process."
            }
        } catch (ex: RemoteException) {
            // Recover gracefully from the process hosting the
            // server dying.
            // For purposes of this sample, put up a notification.
            Toast.makeText(this@Binding, R.string.remote_call_failed, Toast.LENGTH_SHORT).show()
        }
    }

    // ----------------------------------------------------------------------
    // Code showing how to deal with callbacks.
    // ----------------------------------------------------------------------

    /**
     * This implementation is used to receive callbacks from the remote
     * service.
     */
    private val mCallback = object : IRemoteServiceCallback.Stub() {
        /**
         * This is called by the remote service regularly to tell us about
         * new values.  Note that IPC calls are dispatched through a thread
         * pool running in each process, so the code executing here is
         * NOT running in our main thread like most other things. So,
         * to update the UI, we need to use a Handler to hop over there.
         */
        override fun valueChanged(value: Int) {
            handler.sendMessage(handler.obtainMessage(BUMP_MSG, value, 0))
        }
    }

    /**
     * Standard initialization of this activity.  Set up the UI, then wait
     * for the user to interact with it before doing anything.
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.remote_service_binding)

        // Watch for button taps.
        var button: Button = findViewById(R.id.bind)
        button.setOnClickListener(mBindListener)
        button = findViewById(R.id.unbind)
        button.setOnClickListener(unbindListener)
        killButton = findViewById(R.id.kill)
        killButton.setOnClickListener(killListener)
        killButton.isEnabled = false

        callbackText = findViewById(R.id.callback)
        callbackText.text = "Not attached."
        handler = InternalHandler(callbackText)
    }

    private class InternalHandler(
            textView: TextView,
            private val weakTextView: WeakReference<TextView> = WeakReference(textView)
    ) : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                BUMP_MSG -> weakTextView.get()?.text = "Received from service: ${msg.arg1}"
                else -> super.handleMessage(msg)
            }
        }
    }
}

Java

public static class Binding extends Activity {
    /** The primary interface we are calling on the service. */
    IRemoteService mService = null;
    /** Another interface we use on the service. */
    ISecondary secondaryService = null;

    Button killButton;
    TextView callbackText;

    private InternalHandler handler;
    private boolean isBound;

    /**
     * Standard initialization of this activity. Set up the UI, then wait
     * for the user to interact with it before doing anything.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.remote_service_binding);

        // Watch for button taps.
        Button button = (Button)findViewById(R.id.bind);
        button.setOnClickListener(mBindListener);
        button = (Button)findViewById(R.id.unbind);
        button.setOnClickListener(unbindListener);
        killButton = (Button)findViewById(R.id.kill);
        killButton.setOnClickListener(killListener);
        killButton.setEnabled(false);

        callbackText = (TextView)findViewById(R.id.callback);
        callbackText.setText("Not attached.");
        handler = new InternalHandler(callbackText);
    }

    /**
     * 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 is
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            mService = IRemoteService.Stub.asInterface(service);
            killButton.setEnabled(true);
            callbackText.setText("Attached.");

            // We want to monitor the service for as long as we are
            // connected to it.
            try {
                mService.registerCallback(mCallback);
            } catch (RemoteException e) {
                // In this case the service crashes before we can even
                // do anything with it. We can count on soon being
                // disconnected (and then reconnected if it can be restarted)
                // so there is no need to do anything here.
            }

            // As part of the sample, tell the user what happened.
            Toast.makeText(Binding.this, R.string.remote_service_connected,
                    Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service is
            // unexpectedly disconnected&mdash;that is, its process crashed.
            mService = null;
            killButton.setEnabled(false);
            callbackText.setText("Disconnected.");

            // As part of the sample, tell the user what happened.
            Toast.makeText(Binding.this, R.string.remote_service_disconnected,
                    Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * Class for interacting with the secondary interface of the service.
     */
    private ServiceConnection secondaryConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // Connecting to a secondary interface is the same as any
            // other interface.
            secondaryService = ISecondary.Stub.asInterface(service);
            killButton.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName className) {
            secondaryService = null;
            killButton.setEnabled(false);
        }
    };

    private OnClickListener mBindListener = new OnClickListener() {
        public void onClick(View v) {
            // Establish a couple connections with the service, binding
            // by interface names. This lets other applications be
            // installed that replace the remote service by implementing
            // the same interface.
            Intent intent = new Intent(Binding.this, RemoteService.class);
            intent.setAction(IRemoteService.class.getName());
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
            intent.setAction(ISecondary.class.getName());
            bindService(intent, secondaryConnection, Context.BIND_AUTO_CREATE);
            isBound = true;
            callbackText.setText("Binding.");
        }
    };

    private OnClickListener unbindListener = new OnClickListener() {
        public void onClick(View v) {
            if (isBound) {
                // If we have received the service, and hence registered with
                // it, then now is the time to unregister.
                if (mService != null) {
                    try {
                        mService.unregisterCallback(mCallback);
                    } catch (RemoteException e) {
                        // There is nothing special we need to do if the service
                        // crashes.
                    }
                }

                // Detach our existing connection.
                unbindService(mConnection);
                unbindService(secondaryConnection);
                killButton.setEnabled(false);
                isBound = false;
                callbackText.setText("Unbinding.");
            }
        }
    };

    private OnClickListener killListener = new OnClickListener() {
        public void onClick(View v) {
            // To kill the process hosting our service, we need to know its
            // PID.  Conveniently, our service has a call that returns
            // that information.
            if (secondaryService != null) {
                try {
                    int pid = secondaryService.getPid();
                    // Note that, though this API lets us request to
                    // kill any process based on its PID, the kernel
                    // still imposes standard restrictions on which PIDs you
                    // can actually kill.  Typically this means only
                    // the process running your application and any additional
                    // processes created by that app as shown here. Packages
                    // sharing a common UID are also able to kill each
                    // other's processes.
                    Process.killProcess(pid);
                    callbackText.setText("Killed service process.");
                } catch (RemoteException ex) {
                    // Recover gracefully from the process hosting the
                    // server dying.
                    // For purposes of this sample, put up a notification.
                    Toast.makeText(Binding.this,
                            R.string.remote_call_failed,
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    // ----------------------------------------------------------------------
    // Code showing how to deal with callbacks.
    // ----------------------------------------------------------------------

    /**
     * This implementation is used to receive callbacks from the remote
     * service.
     */
    private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
        /**
         * This is called by the remote service regularly to tell us about
         * new values.  Note that IPC calls are dispatched through a thread
         * pool running in each process, so the code executing here is
         * NOT running in our main thread like most other things. So,
         * to update the UI, we need to use a Handler to hop over there.
         */
        public void valueChanged(int value) {
            handler.sendMessage(handler.obtainMessage(BUMP_MSG, value, 0));
        }
    };

    private static final int BUMP_MSG = 1;

    private static class InternalHandler extends Handler {
        private final WeakReference<TextView> weakTextView;

        InternalHandler(TextView textView) {
            weakTextView = new WeakReference<>(textView);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BUMP_MSG:
                    TextView textView = weakTextView.get();
                    if (textView != null) {
                        textView.setText("Received from service: " + msg.arg1);
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
}