Android インターフェース定義言語(AIDL)

Android インターフェース定義言語(AIDL)は、他の IDL と同様に、クライアントとサービスがプロセス間通信(IPC)を使用して相互に通信するために合意するプログラミング インターフェースを定義できます。

Android では、通常、あるプロセスが別のプロセスのメモリにアクセスすることはできません。通信するには、オブジェクトをオペレーティング システムが理解できるプリミティブに分解し、その境界を越えてオブジェクトをマーシャリングする必要があります。このマーシャリングを行うコードは記述が面倒なため、Android では AIDL を使用して処理します。

注: AIDL が必要になるのは、異なるアプリケーションのクライアントが IPC のためにサービスにアクセスできるようにし、サービスでマルチスレッドを処理する場合のみです。異なるアプリケーション間で同時に IPC を実行する必要がない場合は、Binder を実装してインターフェースを作成します。IPC を実行する必要があるが、マルチスレッドを処理する必要がない場合は、Messenger を使用してインターフェースを実装します。いずれにしても、AIDL を実装する前にバインドされたサービスについて理解しておく必要があります。

AIDL インターフェースの設計を始める前に、AIDL インターフェースの呼び出しは直接関数呼び出しであることを認識しておいてください。呼び出しが発生するスレッドについて、前提を置かないでください。呼び出しがローカル プロセスのスレッドから行われるか、リモート プロセスから行われるかによって、動作が異なります。

  • ローカル プロセスから行われた呼び出しは、呼び出しを行っているのと同じスレッドで実行されます。これがメイン UI スレッドである場合、そのスレッドは AIDL インターフェースで引き続き実行されます。別のスレッドの場合は、そのスレッドがサービスでコードを実行します。したがって、ローカル スレッドのみがサービスにアクセスしている場合は、サービス内で実行されるスレッドを完全に制御できます。その場合は、AIDL をまったく使用せず、代わりに Binder を実装してインターフェースを作成します。
  • リモート プロセスからの呼び出しは、プラットフォームが独自のプロセス内に保持するスレッドプールからディスパッチされます。複数の呼び出しが同時に発生する、不明なスレッドからの着信に備えます。つまり、AIDL インターフェースの実装は完全にスレッドセーフである必要があります。同じリモート オブジェクトの 1 つのスレッドから行われた呼び出しは、受信側で順番に受信されます。
  • oneway キーワードは、リモート呼び出しの動作を変更します。これを使用すると、リモート呼び出しはブロックされません。トランザクション データを送信し、すぐに戻ります。インターフェースの実装は、最終的にこれを Binder スレッドプールからの通常の呼び出しとして、通常の遠隔呼び出しとして受け取ります。oneway がローカル呼び出しで使用されている場合、影響はなく、呼び出しは同期のままです。

AIDL インターフェースの定義

Java プログラミング言語の構文を使用して、.aidl ファイルに AIDL インターフェースを定義します。次に、サービスをホストするアプリケーションと、サービスにバインドする他のアプリケーションの両方のソースコード(src/ ディレクトリ)に保存します。

.aidl ファイルを含む各アプリケーションをビルドすると、Android SDK ツールは .aidl ファイルに基づいて IBinder インターフェースを生成し、プロジェクトの gen/ ディレクトリに保存します。サービスは、必要に応じて IBinder インターフェースを実装する必要があります。クライアント アプリケーションは、サービスにバインドし、IBinder からメソッドを呼び出して IPC を実行できます。

AIDL を使用してバインドされたサービスを作成するには、以下の手順を行います。以降のセクションで詳しく説明します。

  1. .aidl ファイルを作成する

    このファイルは、メソッド シグネチャを使用してプログラミング インターフェースを定義します。

  2. インターフェースを実装する

    Android SDK ツールは、.aidl ファイルに基づいて Java プログラミング言語のインターフェースを生成します。このインターフェースには、Binder を拡張し、AIDL インターフェースのメソッドを実装する Stub という名前の内部抽象クラスがあります。Stub クラスを拡張してメソッドを実装する必要があります。

  3. インターフェースをクライアントに公開する

    Service を実装し、onBind() をオーバーライドして Stub クラスの実装を返します。

注意: 最初のリリース後に AIDL インターフェースに加える変更は、サービスを使用する他のアプリケーションが破損しないように、下位互換性を維持する必要があります。つまり、.aidl ファイルを他のアプリケーションにコピーして、それらのアプリケーションがサービスのインターフェースにアクセスできるようにする必要があるため、元のインターフェースのサポートを維持する必要があります。

.aidl ファイルを作成する

AIDL では、パラメータと戻り値を受け取ることができる 1 つ以上のメソッドを持つインターフェースを宣言できるシンプルな構文を使用します。パラメータと戻り値は、他の AIDL 生成インターフェースを含む任意の型にできます。

.aidl ファイルは、Java プログラミング言語を使用して作成する必要があります。各 .aidl ファイルは、単一のインターフェースを定義する必要があり、インターフェース宣言とメソッド シグネチャのみを必要とします。

デフォルトでは、AIDL は次のデータ型をサポートしています。

  • Java プログラミング言語のすべてのプリミティブ型(int、long、char、boolean など。ただし、short を除く)
  • 任意の型の配列(int[]、MyParcelable[] など)
  • String
  • CharSequence
  • List

    List 内のすべての要素は、このリストでサポートされているデータ型のいずれか、または宣言する他の AIDL 生成インターフェースまたは Parcelable のいずれかである必要があります。List は、必要に応じて、List<String> などのパラメータ化された型クラスとして使用できます。もう一端が受け取る実際の具象クラスは常に ArrayList ですが、メソッドは List インターフェースを使用するように生成されます。

  • Map

    Map 内のすべての要素は、このリストでサポートされているデータ型のいずれか、または宣言する他の AIDL 生成インターフェースまたは Parcelable のいずれかである必要があります。Map<String,Integer> 形式などのパラメータ化された型マップはサポートされていません。相手側が受け取る実際の具象クラスは常に HashMap ですが、メソッドは Map インターフェースを使用するように生成されます。Map の代わりに Bundle を使用することを検討してください。

以前にリストされていない追加の型ごとに import ステートメントを含める必要があります。これは、インターフェースと同じパッケージで定義されている場合でも同様です。

サービス インターフェースを定義する際は、次の点に注意してください。

  • メソッドは 0 個以上のパラメータを受け取ることができ、値または void を返すことができます。
  • プリミティブ以外のパラメータはすべて、データの方向を示す方向タグ(in、out、inout)を必要とします(下記の例を参照)。

    プリミティブ、String、IBinder、AIDL で生成されたインターフェースは、デフォルトで in であり、それ以外にすることはできません。

    注意: パラメータのマーシャリングは負荷が高いため、方向は本当に必要なものに限定してください。

  • .aidl ファイルに含まれるすべてのコードコメントは、インポート ステートメントとパッケージ ステートメントの前のコメントを除き、生成された IBinder インターフェースに含まれます。
  • 文字列定数と int 定数は、const int VERSION = 1; などの AIDL インターフェースで定義できます。
  • メソッド呼び出しは、通常はインターフェースのメソッド インデックスに基づく transact() コードによってディスパッチされます。これによりバージョニングが困難になるため、トランザクション コードをメソッドに手動で割り当てることができます(void method() = 10;)。
  • null 値許容の引数と戻り値の型には、@nullable を使用してアノテーションを付ける必要があります。

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

.aidl ファイルをプロジェクトの src/ ディレクトリに保存します。アプリケーションをビルドすると、SDK Tools によってプロジェクトの gen/ ディレクトリに IBinder インターフェース ファイルが生成されます。生成されたファイルの名前は .aidl ファイルの名前と一致しますが、拡張子は .java です。たとえば、IRemoteService.aidl の結果は IRemoteService.java になります。

Android Studio を使用している場合、増分ビルドによってバインダークラスがほぼ即座に生成されます。Android Studio を使用していない場合は、次回アプリをビルドするときに Gradle ツールによってバインダークラスが生成されます。.aidl ファイルの作成が完了したら、すぐに gradle assembleDebug または gradle assembleRelease を使用してプロジェクトをビルドし、生成されたクラスにコードをリンクできるようにします。

インターフェースを実装する

アプリケーションをビルドすると、Android SDK ツールによって、.aidl ファイルにちなんだ名前の .java インターフェース ファイルが生成されます。生成されたインターフェースには、Stub という名前のサブクラスが含まれています。これは、親インターフェース(YourInterface.Stub など)の抽象実装であり、.aidl ファイルのすべてのメソッドを宣言します。

注: Stub には、いくつかのヘルパー メソッドも定義されています。特に asInterface() は、IBinder(通常はクライアントの onServiceConnected() コールバック メソッドに渡されるもの)を受け取り、スタブ インターフェースのインスタンスを返します。このキャストを行う方法について詳しくは、IPC メソッドの呼び出しをご覧ください。

.aidl から生成されたインターフェースを実装するには、生成された Binder インターフェース(YourInterface.Stub など)を拡張し、.aidl ファイルから継承されたメソッドを実装します。

次の例は、前の IRemoteService.aidl の例で定義された IRemoteService というインターフェースを、匿名インスタンスを使用して実装したものです。

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

binder は Stub クラス(Binder)のインスタンスになり、サービスの IPC インターフェースを定義します。次のステップでは、このインスタンスがクライアントに公開され、クライアントがサービスを操作できるようになります。

AIDL インターフェースを実装する際は、次のルールに注意してください。

  • 着信呼び出しがメインスレッドで実行されるとは限らないため、最初からマルチスレッドを考慮し、スレッドセーフになるようにサービスを適切に構築する必要があります。
  • デフォルトでは、IPC 呼び出しは同期的です。サービスがリクエストを完了するまでに数ミリ秒以上かかることがわかっている場合は、アクティビティのメインスレッドからサービスを呼び出さないでください。アプリケーションがハングし、Android に「アプリケーション応答なし」ダイアログが表示される可能性があります。クライアントの別のスレッドから呼び出します。
  • Parcel.writeException() のリファレンス ドキュメントに記載されている例外タイプのみが呼び出し元に返されます。

クライアントにインターフェースを公開する

サービス用のインターフェースを実装したら、クライアントがバインドできるように、インターフェースをクライアントに公開する必要があります。サービスのインターフェースを公開するには、Service を拡張し、onBind() を実装して、生成された Stub を実装するクラスのインスタンスを返します(前述のとおり)。IRemoteService のサンプル インターフェースをクライアントに公開するサービスの例を次に示します。

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

これで、アクティビティなどのクライアントが bindService() を呼び出してこのサービスに接続すると、クライアントの onServiceConnected() コールバックは、サービスの onBind() メソッドによって返された binder インスタンスを受け取ります。

クライアントはインターフェース クラスにもアクセスできる必要があります。したがって、クライアントとサービスが別々のアプリケーションにある場合、クライアントのアプリケーションの src/ ディレクトリに .aidl ファイルのコピーが必要です。このファイルは android.os.Binder インターフェースを生成し、クライアントに AIDL メソッドへのアクセスを提供します。

クライアントは、onServiceConnected() コールバックで IBinder を受け取ると、YourServiceInterface.Stub.asInterface(service) を呼び出して、返されたパラメータを YourServiceInterface 型にキャストする必要があります。

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

その他のサンプルコードについては、ApiDemos の RemoteService.java クラスをご覧ください。

IPC 経由でオブジェクトを渡す

Android 10(API レベル 29 以降)では、AIDL で直接 Parcelable オブジェクトを定義できます。AIDL インターフェースの引数としてサポートされている型と、その他の Parcelable もサポートされています。これにより、マーシャリング コードとカスタムクラスを手動で作成する追加作業が不要になります。ただし、これにより、ベア構造体も作成されます。カスタム アクセサやその他の機能が必要な場合は、代わりに 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;
}

上記のコードサンプルでは、整数フィールド left、top、right、bottom を含む Java クラスが自動的に生成されます。関連するすべてのマーシャリング コードが自動的に実装され、実装を追加することなくオブジェクトを直接使用できます。

IPC インターフェースを介して、あるプロセスから別のプロセスにカスタムクラスを送信することもできます。ただし、クラスのコードが IPC チャネルのもう一方の側で使用可能であることを確認してください。また、クラスは Parcelable インターフェースをサポートしている必要があります。Parcelable をサポートすることは重要です。これにより、Android システムはオブジェクトをプリミティブに分解し、プロセス間でマーシャリングできるようになります。

Parcelable をサポートするカスタムクラスを作成する手順は次のとおりです。

  1. クラスに Parcelable インターフェースを実装します。
  2. writeToParcel を実装します。これは、オブジェクトの現在の状態を取得して Parcel に書き込みます。
  3. Parcelable.Creator インターフェースを実装するオブジェクトである CREATOR という静的フィールドをクラスに追加します。
  4. 最後に、次の Rect.aidl ファイルに示すように、Parcelable クラスを宣言する .aidl ファイルを作成します。

    カスタム ビルドプロセスを使用している場合は、.aidl ファイルをビルドに追加しないでください。C 言語のヘッダー ファイルと同様に、この .aidl ファイルはコンパイルされません。

AIDL は、生成するコード内でこれらのメソッドとフィールドを使用して、オブジェクトのマーシャリングとアンマーシャリングを行います。

たとえば、次の Rect.aidl ファイルは、Parcelable な Rect クラスを作成します。

package android.graphics;

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

Rect クラスが Parcelable プロトコルを実装する例を次に示します。

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

Rect クラスのマーシャリングは簡単です。Parcel の他のメソッドを確認して、Parcel に書き込むことができる他の種類の値を確認してください。

警告: 他のプロセスからデータを受信することのセキュリティ上の影響に注意してください。この場合、Rect は Parcel から 4 つの数値を読み取りますが、呼び出し元が何をしようとしているかに応じて、これらの数値が許容範囲内にあることを確認する必要があります。マルウェアからアプリケーションを保護する方法について詳しくは、アプリケーション セキュリティのヒントをご覧ください。

Parcelable を含む Bundle 引数を持つメソッド

メソッドが、Parcelable を含むことが想定される Bundle オブジェクトを受け入れる場合は、Bundle からの読み取りを試みる前に、Bundle.setClassLoader(ClassLoader) を呼び出して Bundle のクラスローダを設定してください。そうしないと、アプリで Parcelable が正しく定義されていても、ClassNotFoundException が発生します。

たとえば、次のサンプル .aidl ファイルについて考えてみます。

// 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);
}
次の実装に示すように、Rect を読み取る前に、ClassLoader が Bundle で明示的に設定されています。
private val binder = object : IRectInsideBundle.Stub() {
    override fun saveRect(bundle: Bundle) {
        bundle.classLoader = classLoader
        val rect = BundleCompat.getParcelable(bundle, "rect", Rect::class.java)
        process(rect) // Do more with the parcelable.
    }
}

IPC メソッドを呼び出す

AIDL で定義されたリモート インターフェースを呼び出すには、呼び出し元のクラスで次の手順を行います。

  1. プロジェクトの src/ ディレクトリに .aidl ファイルを含めます。
  2. AIDL に基づいて生成される IBinder インターフェースのインスタンスを宣言します。
  3. ServiceConnection を実装する。
  4. Context.bindService() を呼び出して、ServiceConnection の実装を渡します。
  5. onServiceConnected() の実装では、service という IBinder インスタンスを受け取ります。YourInterfaceName.Stub.asInterface((IBinder)service) を呼び出して、返されたパラメータを YourInterface 型にキャストします。
  6. インターフェースで定義したメソッドを呼び出します。接続が切断されたときにスローされる DeadObjectException 例外を常にトラップします。また、SecurityException 例外をトラップします。この例外は、IPC メソッド呼び出しに関係する 2 つのプロセスで AIDL 定義が競合している場合にスローされます。
  7. 接続を解除するには、インターフェースのインスタンスを使用して Context.unbindService() を呼び出します。

IPC サービスを呼び出す際は、次の点に注意してください。

  • オブジェクトはプロセス間で有効な参照です。
  • 匿名オブジェクトをメソッド引数として送信できます。

サービスへのバインドの詳細については、バインドされたサービスの概要をご覧ください。

以下に、AIDL で作成されたサービスを呼び出すサンプルコードを示します。これは、ApiDemos プロジェクトのリモート サービス サンプルから抜粋したものです。

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