Android进程间通信例子
步骤
打开androidstudio
首先在src/main/aidl 创建adil文件夹。
package aidlserver.app;
import aidlserver.app.BankCount;
interface IBook {
void borrowBook(String number, int count);
void sendData(in BankCount bank);
}
BankCount 自定义Parcelable对象,需在同包下声明
package aidlserver.app;
parcelable BankCount;
package aidlserver.app
import android.os.Parcel
import android.os.Parcelable
class BankCount() : Parcelable {
var type: Int = 1
var account: String = ""
var name: String = "123456"
var passwd: String = "liulei"
constructor(parcel: Parcel) : this() {
type = parcel.readInt()
account = parcel.readString() ?: ""
name = parcel.readString() ?: ""
passwd = parcel.readString() ?: ""
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(type)
parcel.writeString(account)
parcel.writeString(name)
parcel.writeString(passwd)
}
override fun describeContents(): Int {
return 0
}
override fun toString(): String {
return "BankCount(type=$type, account='$account', name='$name', passwd='$passwd')"
}
companion object CREATOR : Parcelable.Creator<BankCount> {
override fun createFromParcel(parcel: Parcel): BankCount {
return BankCount(parcel)
}
override fun newArray(size: Int): Array<BankCount?> {
return arrayOfNulls(size)
}
}
}
在aidlServer module下创建BookService
package aidlserver.app
import android.app.Notification
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.widget.Toast
import androidx.core.app.NotificationChannelCompat
import androidx.core.app.NotificationManagerCompat
class BookService : Service() {
private var handler = Handler(Looper.getMainLooper())
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannelCompat.Builder(
"bookService",
NotificationManagerCompat.IMPORTANCE_DEFAULT
)
.setName("bookServiceChannel")
.build()
val notification = Notification.Builder(this, channel.id)
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("Aidl Book Service Demo")
.build()
NotificationManagerCompat.from(this).createNotificationChannel(channel)
startForeground(1, notification)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
println("xxxx onStartCommand")
return super.onStartCommand(intent, flags, startId)
}
private var myBinder = object : IBook.Stub() {
override fun borrowBook(number: String?, count: Int) {
println("xxxx borrow number = $number count = $count")
handler.post {
Toast.makeText(
this@BookService,
"borrowBook $number $count",
Toast.LENGTH_SHORT
).show()
}
}
override fun sendData(bank: BankCount?) {
println("IBook binder sendData $bank")
}
}
override fun onBind(p0: Intent?): IBinder {
return myBinder
}
}
客户端运行示例代码:
package com.example.aidlclient
import aidlserver.app.BankCount
import aidlserver.app.IBook
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.aidlclient.databinding.ActivityMainBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private var serviceConnection: ServiceConnection? = null
private var iBookInterface: IBook? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
viewBinding.test.setOnClickListener {
if (iBookInterface == null) {
Toast.makeText(it.context, "未获取到binder对象", Toast.LENGTH_SHORT).show()
} else {
iBookInterface?.borrowBook("you are best!", 202288)
lifecycleScope.launch {
delay(500L)
BankCount().apply {
account = "leige"
name = "12"
type = 1
passwd = "123456"
iBookInterface?.sendData(this)
}
}
}
}
serviceConnection = object : ServiceConnection {
override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
println("xxxx onServiceConnected p0 = [${p0}], p1 = [${p1}]")
val iBook: IBook = IBook.Stub.asInterface(p1)
iBookInterface = iBook
}
override fun onServiceDisconnected(p0: ComponentName?) {
println("xxxx onServiceDisconnected p0 = [${p0}]")
}
}
val ret = bindService(
getServiceIntent(),
serviceConnection as ServiceConnection,
Service.BIND_AUTO_CREATE
)
if (!ret) {
unbindService(serviceConnection as ServiceConnection)
}
println("xxxx bindService ret = $ret")
}
private fun getServiceIntent(): Intent {
val intent = Intent("aidlserver.app.BookService")
intent.setPackage("aidlserver.app")
return intent
}
override fun onDestroy() {
super.onDestroy()
try {
serviceConnection?.let { unbindService(it) }
} catch (ex: Throwable) {
ex.printStackTrace()
}
}
}
最后附上项目地址:
https://gitee.com/liulei9385/android-binder-demo
|