AIDL的简单使用

801 阅读1分钟

AIDL可实现进程进程间通信,两个APP之间可以通过AIDL进行数据传递。 AIDL分为服务端,客户端,这里实现消息单向发送,即从服务端到客户端。 简单使用:

服务端:

  1. 创建AIDL文件,添加一个用于传递数据的抽象函数fun,sync project;
  2. 创建Service,实现aidl.Stub接口binder,实现fun,返回binder,注册Service; 客户端:
  3. 将服务端的AIDL文件复制到客户端;
  4. 通过bindService启动服务器创建的Service 实例代码:(Practice为服务器,TestPractice为客户端)
1.创建AIDL文件
//创建的AIDL文件
interface IMyAidlInterface {
    /**
     * 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);

    String getName();   //用于数据通信的抽象函数

}
2. 创建Service
class MyService : Service() {
        var flag = 0;   //设置变量

    override fun onBind(intent: Intent): IBinder {
        return binder
    }
    private val binder = object :IMyAidlInterface.Stub(){
        override fun basicTypes(
            anInt: Int,
            aLong: Long,
            aBoolean: Boolean,
            aFloat: Float,
            aDouble: Double,
            aString: String?
        ) {
        }

        override fun getName(): String {
            flag++
            return "test:$flag"
        }

    }
}

//注册Service
<service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>

Practise 项目目录结构:

3.在TestPractise中创建aidl.com.example.practise,将Practise项目的aidl复制到该文件夹。TestPractise项目结构:

4.启动Service
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var imyAidl:IMyAidlInterface?=null
        
        val intent = Intent().setComponent(
            ComponentName("com.example.practise","com.example.practise.MyService"))
        bindService(intent,object :ServiceConnection{
            override fun onServiceDisconnected(name: ComponentName?) {
                imyAidl=null    //释放对象,便于回收
                Log.d("009"," stop connect")
            }

            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                imyAidl=IMyAidlInterface.Stub.asInterface(service)
                Log.d("009"," start connect")
            }
        }, Context.BIND_AUTO_CREATE)

        findViewById<Button>(R.id.bt).setOnClickListener(View.OnClickListener {
            try {
                Toast.makeText(applicationContext, imyAidl?.name, Toast.LENGTH_SHORT).show()
            }catch (e:RemoteException){
                e.printStackTrace()
            }
        })
    }

}