Android aidl的使用方法

1、AIDL的作用

AIDL是用于Android的IPC通讯的,因此可以在一个APP内部通讯,也可以创建两个APP之间进行通讯。

AIDL的职能分配很明确,Service作为后台运行作为服务器管理各种交互,Client作为客户端请求数据或调用Service的方法。

2、AIDL的简单使用

1)创建一个aidl文件,直接右键创建就可以了,

package com.example.mytest;
// IMyAidlInterface.aidl
package com.example.mytest;

// Declare any non-default types here with import statements

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 add(int x , int y);
}

2)选中刚刚建立的 .aidl文件 生产对应的java文件。

AndroidStudio 可以通过Build--》model App 完成

3)编写Service的具体对象 实现接口

package com.example.mytest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class FirstService extends Service {
    public FirstService() {
    }

    private static String Tag = "FirstService";

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        Log.d(Tag,"service on bind");
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(Tag,"OnCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(Tag,"onStartCommand");
        return START_STICKY;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(Tag,"onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(Tag,"onDestroy");
    }





    IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub(){

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public String add(int x, int y) throws RemoteException {
            Log.d(Tag,x + "--" + y);
            return String.valueOf(x + y);
        }
    };
}

注意:onBund 返回IBinder类型,为了后面的回调会调动

4)确定一下AndroidManifest.xml里面的Service内容

        <service
            android:name=".FirstService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.mytest.aidl.FirstService"/>
            </intent-filter>

        </service>

5)打开服务

    private Button btnStartService; 
    private Button btnBindService;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        tvId = (TextView) findViewById(R.id.tv_id);

        btnStartService = (Button) findViewById(R.id.btn_Start_Service);
        btnStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setPackage("com.example.mytest");
                intent.setAction("com.example.mytest.aidl.FirstService");
                startService(intent);
            }
        });

        btnBindService = (Button) findViewById(R.id.btnBindService);
        btnBindService.setOnClickListener(new View.OnClickListener() {
            @Override
                public void onClick(View view) {
                        bind();
                }
        });
    

    private void bind(){
        Log.d(Tag, "bind");
        Intent intent = new Intent();
        intent.setPackage("com.example.mytest");
        if(controllerConnection != null){
            this.bindService(intent,controllerConnection,this.BIND_AUTO_CREATE);//绑定服务,建立链接
        }
        else {
            Log.d(Tag, "controllerConnection != null");
        }
    }

    private void unbind(){
        if(controllerConnection != null && myAIDLController.asBinder().isBinderAlive()){
            try{
                Log.d(Tag, "this.unbindService(controllerConnection);");
                this.unbindService(controllerConnection);
            } catch (Exception localException) {
                Log.w(Tag, "unbind Exception localException");
            }
        }
    }

在bind的时候是异步的,因此可以通过onServiceConnected()来判断绑定上后的操作。

private ServiceConnection controllerConnection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d(Tag,"onServiceConnected");

            myAIDLController = IMyAidlInterface.Stub.asInterface(iBinder);
            if (myAIDLController != null) {
                try {
                    Log.d(Tag, "ServiceConnection success");
                    Toast.makeText(MainActivity.this, "ServiceConnection success", Toast.LENGTH_LONG).show();
                } catch (Exception localException) {
                    Log.w(Tag, "Exception localException");
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d(Tag,"onServiceDisconnected");
            Toast.makeText(MainActivity.this, "onServiceDisconnected", Toast.LENGTH_LONG).show();

            myAIDLController = null;
        }

        @Override
        public void onBindingDied(ComponentName name) {
            Log.d(Tag,"onBindingDied");
        }

        @Override
        public void onNullBinding(ComponentName name) {
            Log.d(Tag,"onNullBinding");
        }
    };

6)调用Service方法add()

调用的时候需要绑定Service方法,上面已经有了,接下来调用就简单了,创建一个Button,然后拿到Service的控制对象,调用方法add

        btnServiceFunc = (Button) findViewById(R.id.btnServiceFunc);
        btnServiceFunc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Log.d(Tag, String.valueOf( myAIDLController.add(1,2)));
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android AIDLAndroid Interface Definition Language)是一种用于定义客户端和服务之间通信接口的语言。AIDL 是一个 Android 特有的 RPC(远程过程调用)机制。 下面是使用 AIDL 的基本步骤: 1. 定义 AIDL 接口 在服务端创建一个 AIDL 文件,定义服务的接口方法。例如,创建一个名为 IMyService.aidl 的文件,其中包含以下内容: ``` interface IMyService { void sayHello(); } ``` 2. 实现 AIDL 接口 在服务端实现 AIDL 接口,例如: ``` public class MyService extends Service { private final IMyService.Stub binder = new IMyService.Stub() { @Override public void sayHello() throws RemoteException { Log.i("MyService", "Hello World"); } }; @Nullable @Override public IBinder onBind(Intent intent) { return binder; } } ``` 3. 绑定服务 在客户端绑定服务,例如: ``` private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { IMyService myService = IMyService.Stub.asInterface(service); try { myService.sayHello(); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } }; private void bindService() { Intent intent = new Intent(this, MyService.class); bindService(intent, connection, Context.BIND_AUTO_CREATE); } ``` 通过上述步骤,就可以实现客户端与服务端之间的通信。需要注意的是,AIDL 接口中定义的方法必须是可序列化的。如果方法参数或返回值类型不支持序列化,可以通过 Parcelable 接口实现序列化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值