美文网首页
AS中使用AIDL

AS中使用AIDL

作者: CloudFlyKing | 来源:发表于2017-11-28 16:47 被阅读0次

AIDL 介绍:

AIDL 是 Android Interface definition language的缩写,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口。

新建两个小demo

server.png
client.png

这里新建两个工程,一个服务端,一个客户端,用于实践。

AIDL文件

在server端新建一个aidl文件,操作如下:


新建aidl文件.png

新建之后的目录结构如下:


新建后的目录结构.png
打开刚才新建的aidl文件:
aidl文件.png

如果需要定义一些非基本类型的类,也需要放在和AIDL文件同目录下。

将整个AIDL文件拷贝到客户端同样的目录下面:


拷贝到客户端.png

两端都编译一下,系统会生成对应的接口类:


生成的接口类.png

Server端开发

在Server端,创建一个Service:


新建的Service.png

在配置文件中注册一下:


注册Service.png

Client端开发

在Clinet端简单的隐式启动刚才的Service,然后取得那个IBinder对象,转换为IMyAidlInterface对象,再调接口:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private Button clickButton;
    private TextView showTextView;

    private String action = "net.wyf.myaidlserver.service.MyService";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        clickButton = findViewById(R.id.clickId);
        showTextView = findViewById(R.id.answerId);
        bind();
        clickButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (aidlInterface != null) {
                    try {
                        double add = aidlInterface.add(1.3, 2.4);
                        Log.d(TAG, "onClick: "+ add);
                        showTextView.setText(add + "");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                        showTextView.setText("fail");
                    }
                } else {
                    Log.e(TAG, "fail");
                    showTextView.setText("fail");
                }

            }
        });
    }

    IMyAidlInterface aidlInterface;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            aidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e(TAG, "onServiceDisconnected: ");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }

    private void bind() {
        Intent intent = new Intent(action);
        intent.setPackage("net.wyf.myaidlserver");
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }
}

注意:隐式启动Service的时候千万不要忘记加包名。

运行结果

客户端打印.png 服务端打印.png

一个简单的例子实现了。
MyAIDLClient:https://gitee.com/xiaobindegushi/MyAIDLClient
MyAIDLServer:https://gitee.com/xiaobindegushi/MyAIDLServer

相关文章

网友评论

      本文标题:AS中使用AIDL

      本文链接:https://www.haomeiwen.com/subject/rjrebxtx.html