| class MainActivity : AppCompatActivity() {
val connect = object :ServiceConnection{
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val reply = Parcel.obtain()
val sendData = Parcel.obtain()
service?.transact(GET_ASH_MEMORY, sendData, reply, 0 ) //传输信号GET_ASH_MEMORY
val pfd = reply.readParcelable<ParcelFileDescriptor>(javaClass.classLoader)
val descriptor = pfd?.fileDescriptor //拿到fd
val size = reply.readInt() //拿到长度
val input = FileInputStream(descriptor)
val bytes = input.readBytes()
val message = String(bytes, 0 , size, Charsets.UTF_8) //生成string
Toast.makeText( this @MainActivity ,message,Toast.LENGTH_SHORT).show()
}
override fun onServiceDisconnected(name: ComponentName?) {
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<TextView>(R.id.intent).setOnClickListener {
//启动服务
bindService(Intent( this ,MyService:: class .java),connect, Context.BIND_AUTO_CREATE) |