Android 인터페이스 정의 언어(AIDL)는 다른 IDL과 유사합니다. AIDL을 사용하면 클라이언트와 서비스가 프로세스 간 통신(IPC)을 사용하여 서로 통신하기 위해 합의한 프로그래밍 인터페이스를 정의할 수 있습니다.
Android에서는 한 프로세스가 다른 프로세스의 메모리에 정상적으로 액세스할 수 없습니다. 통신하려면 객체를 운영체제가 이해할 수 있는 기본 요소로 분해하고 경계를 넘어 객체를 마샬링해야 합니다. 마샬링을 실행하는 코드는 작성하기가 지루하므로 Android는 AIDL을 사용하여 이를 처리합니다.
참고: AIDL은 다른 애플리케이션의 클라이언트가 IPC를 위해 서비스에 액세스하도록 허용하고 서비스에서 멀티스레딩을 처리하려는 경우에만 필요합니다. 여러 애플리케이션에서 동시 IPC를 실행할 필요가 없다면 Binder를 구현하여 인터페이스를 만듭니다.
IPC를 실행하고 싶지만 멀티스레딩을 처리할 필요가 없는 경우 Messenger를 사용하여 인터페이스를 구현합니다.
어떤 경우든 AIDL을 구현하기 전에 바인드된 서비스를 이해해야 합니다.
AIDL 인터페이스 설계를 시작하기 전에 AIDL 인터페이스 호출은 직접 함수 호출이라는 점에 유의하세요. 호출이 발생하는 스레드에 관해 가정하지 마세요. 호출이 로컬 프로세스의 스레드에서 발생하는지 원격 프로세스에서 발생하는지에 따라 결과가 달라집니다.
- 로컬 프로세스에서 이루어진 호출은 호출을 수행하는 동일한 스레드에서 실행됩니다. 이 스레드가 기본 UI 스레드인 경우 AIDL 인터페이스에서 계속 실행됩니다. 다른 스레드인 경우 서비스에서 코드를 실행하는 스레드입니다. 따라서 로컬 스레드만 서비스에 액세스하는 경우 서비스에서 실행되는 스레드를 완전히 제어할 수 있습니다. 하지만 이 경우에는 AIDL을 전혀 사용하지 마세요. 대신
Binder를 구현하여 인터페이스를 만드세요. - 원격 프로세스의 호출은 플랫폼이 자체 프로세스 내에서 유지하는 스레드 풀에서 전달됩니다. 알 수 없는 대화목록에서 걸려오는 수신 전화에 대비하고, 여러 통화가 동시에 발생할 수 있습니다. 즉, AIDL 인터페이스 구현은 완전히 스레드로부터 안전해야 합니다. 동일한 원격 객체의 한 스레드에서 이루어진 호출은 수신자 측에 순서대로 도착합니다.
oneway키워드는 원격 호출의 동작을 수정합니다. 이 옵션을 사용하면 원격 호출이 차단되지 않습니다. 트랜잭션 데이터를 전송하고 즉시 반환합니다. 인터페이스 구현은 결국 이를Binder스레드 풀의 일반 호출로 수신합니다.oneway가 로컬 호출과 함께 사용되는 경우 영향이 없으며 호출은 여전히 동기식입니다.
AIDL 인터페이스 정의
Java 프로그래밍 언어 문법을 사용하여 .aidl 파일에 AIDL 인터페이스를 정의한 다음 서비스를 호스팅하는 애플리케이션과 서비스에 바인딩하는 다른 애플리케이션의 소스 코드(src/ 디렉터리)에 저장합니다.
.aidl 파일이 포함된 각 애플리케이션을 빌드하면 Android SDK 도구는 .aidl 파일을 기반으로 IBinder 인터페이스를 생성하고 프로젝트의 gen/ 디렉터리에 저장합니다. 서비스는 적절하게 IBinder 인터페이스를 구현해야 합니다. 그러면 클라이언트 애플리케이션이 서비스에 바인딩하고 IBinder에서 메서드를 호출하여 IPC를 실행할 수 있습니다.
AIDL을 사용하여 바인딩된 서비스를 만들려면 다음 섹션에 설명된 단계를 따르세요.
.aidl파일 만들기이 파일은 메서드 서명으로 프로그래밍 인터페이스를 정의합니다.
- 인터페이스 구현
Android SDK 도구는
.aidl파일을 기반으로 Java 프로그래밍 언어로 인터페이스를 생성합니다. 이 인터페이스에는Binder를 확장하고 AIDL 인터페이스의 메서드를 구현하는Stub라는 내부 추상 클래스가 있습니다.Stub클래스를 확장하고 메서드를 구현해야 합니다. - 클라이언트에 인터페이스 노출
주의: 첫 번째 출시 후 AIDL 인터페이스를 변경하는 경우 서비스를 사용하는 다른 애플리케이션이 중단되지 않도록 하위 호환성을 유지해야 합니다. 즉, .aidl 파일은 다른 애플리케이션이 서비스의 인터페이스에 액세스할 수 있도록 다른 애플리케이션에 복사되어야 하므로 원본 인터페이스에 대한 지원을 유지해야 합니다.
.aidl 파일 만들기
AIDL은 매개변수와 반환 값을 사용할 수 있는 하나 이상의 메서드로 인터페이스를 선언할 수 있는 간단한 문법을 사용합니다. 매개변수와 반환 값은 어떤 유형이든 가능하며, 다른 AIDL 생성 인터페이스도 가능합니다.
Java 프로그래밍 언어를 사용하여 .aidl 파일을 구성해야 합니다. 각 .aidl 파일은 단일 인터페이스를 정의해야 하며 인터페이스 선언 및 메서드 서명만 필요합니다.
기본적으로 AIDL은 다음 데이터 유형을 지원합니다.
- Java 프로그래밍 언어의 모든 기본 유형(
short제외)(예:int,long,char,boolean등) - 모든 유형의 배열(예:
int[]또는MyParcelable[]) StringCharSequenceListList의 모든 요소는 이 목록에서 지원되는 데이터 유형 중 하나이거나 선언하는 다른 AIDL 생성 인터페이스 또는 parcelable 중 하나여야 합니다.List는 선택적으로 매개변수화된 유형 클래스(예:List<String>)로 사용할 수 있습니다. 다른 쪽에서 수신하는 실제 구체적인 클래스는 항상ArrayList입니다. 단, 메서드는List인터페이스를 사용하도록 생성됩니다.MapMap의 모든 요소는 이 목록에서 지원되는 데이터 유형 중 하나이거나 선언하는 다른 AIDL 생성 인터페이스 또는 parcelable 중 하나여야 합니다.Map<String,Integer>형식과 같은 매개변수화된 유형 맵은 지원되지 않습니다. 다른 쪽에서 수신하는 실제 구체적인 클래스는 항상HashMap입니다. 단, 메서드는Map인터페이스를 사용하도록 생성됩니다.Map대신Bundle을 사용하는 것이 좋습니다.
이전에 나열되지 않은 각 추가 유형에 대해 import 문을 포함해야 합니다(인터페이스와 동일한 패키지에 정의된 경우에도 포함).
서비스 인터페이스를 정의할 때는 다음 사항에 유의하세요.
- 메서드는 0개 이상의 매개변수를 사용할 수 있으며 값 또는 void를 반환할 수 있습니다.
- 모든 비기본 매개변수에는 데이터가 이동하는 방향을 나타내는 방향 태그(
in,out또는inout)가 필요합니다(아래 예 참고).기본 요소,
String,IBinder, AIDL 생성 인터페이스는 기본적으로in이며 다른 값일 수 없습니다.주의: 매개변수 마샬링은 비용이 많이 들기 때문에 방향을 실제로 필요한 것으로 제한하세요.
.aidl파일에 포함된 모든 코드 주석은 가져오기 및 패키지 문 앞의 주석을 제외하고 생성된IBinder인터페이스에 포함됩니다.- 문자열 및 int 상수는 AIDL 인터페이스(예:
const int VERSION = 1;)에서 정의할 수 있습니다. - 메서드 호출은
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); }
프로젝트의 src/ 디렉터리에 .aidl 파일을 저장합니다. 애플리케이션을 빌드하면 SDK 도구는 프로젝트의 gen/ 디렉터리에 IBinder 인터페이스 파일을 생성합니다. 생성된 파일의 이름은 .aidl 파일의 이름과 일치하지만 .java 확장자가 있습니다. 예를 들어 IRemoteService.aidl는 IRemoteService.java를 반환합니다.
Android 스튜디오를 사용하는 경우 증분 빌드는 거의 즉시 바인더 클래스를 생성합니다.
Android 스튜디오를 사용하지 않는 경우 다음에 애플리케이션을 빌드할 때 Gradle 도구가 바인더 클래스를 생성합니다. .aidl 파일 작성을 완료하는 즉시 gradle assembleDebug 또는 gradle assembleRelease로 프로젝트를 빌드하여 코드가 생성된 클래스에 연결될 수 있도록 합니다.
인터페이스 구현
애플리케이션을 빌드하면 Android SDK 도구는 .aidl 파일의 이름을 딴 .java 인터페이스 파일을 생성합니다. 생성된 인터페이스에는 상위 인터페이스(예: YourInterface.Stub)의 추상 구현인 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는 서비스의 IPC 인터페이스를 정의하는 Stub 클래스(Binder)의 인스턴스입니다. 다음 단계에서는 클라이언트가 서비스와 상호작용할 수 있도록 이 인스턴스가 클라이언트에 노출됩니다.
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를 지원하는 커스텀 클래스를 만들려면 다음 단계를 따르세요.
- 클래스가
Parcelable인터페이스를 구현하도록 합니다. - 객체의 현재 상태를 가져와
Parcel에 쓰는writeToParcel를 구현합니다. Parcelable.Creator인터페이스를 구현하는 객체인 클래스에CREATOR라는 정적 필드를 추가합니다.- 마지막으로 다음
Rect.aidl파일과 같이 parcelable 클래스를 선언하는.aidl파일을 만듭니다.커스텀 빌드 프로세스를 사용하는 경우
.aidl파일을 빌드에 추가하지 마세요. C 언어의 헤더 파일과 마찬가지로 이.aidl파일은 컴파일되지 않습니다.
AIDL은 생성하는 코드에서 이러한 메서드와 필드를 사용하여 객체를 마샬링 및 마샬링 해제합니다.
예를 들어 다음은 parcelable인 Rect 클래스를 만드는 Rect.aidl 파일입니다.
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에서 네 개의 숫자를 읽지만, 호출자가 수행하려는 작업에 허용되는 값 범위 내에 있는지 확인하는 것은 개발자의 책임입니다. 멀웨어로부터 애플리케이션을 안전하게 보호하는 방법에 관한 자세한 내용은 애플리케이션 보안 도움말을 참고하세요.
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); }
ClassLoader는 Rect를 읽기 전에 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로 정의된 원격 인터페이스를 호출하려면 호출 클래스에서 다음 단계를 따르세요.
- 프로젝트
src/디렉터리에.aidl파일을 포함합니다. - AIDL을 기반으로 생성된
IBinder인터페이스의 인스턴스를 선언합니다. ServiceConnection를 구현합니다.Context.bindService()를 호출하여ServiceConnection구현을 전달합니다.onServiceConnected()구현에서service라는IBinder인스턴스를 수신합니다.YourInterfaceName.Stub.asInterface((IBinder)service)를 호출하여 반환된 매개변수를YourInterface유형으로 변환합니다.- 인터페이스에 정의한 메서드를 호출합니다. 연결이 끊어질 때 발생하는
DeadObjectException예외를 항상 트랩합니다. 또한 IPC 메서드 호출에 관련된 두 프로세스에 충돌하는 AIDL 정의가 있을 때 발생하는SecurityException예외를 트랩합니다. - 연결을 해제하려면 인터페이스 인스턴스로
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—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) } } } }