AIDL 学习小结

来源:互联网 发布:智能手机看书软件 编辑:程序博客网 时间:2024/06/06 13:10

前言

      在进程通信中,android可以用AIDL 来进行进程之间的通信,aidl(android inteface definition Language) ;

一. 步骤1: 写服务端相关代码 

     1) 写服务端代码,本例在com.example.aidl_serer  下 新建  AIDLTest.aidl  文件,如下图所示:

.

  2) AIDLTest.aidl 文件内容如下:


3)当写完这些,在gen\com.example.aidl_serer \下会有AIDLTest.java文件生成. 如下图所示,AIDLTest.java是在编译器的帮助下生成,其内部类Stub继承Binder接口并实现了我们定义的AIDLTest接口,它的asInterface( )方法最重要, 能 将IBinder 对象转成 AIDLTest对象.这在后续客户端与服务器通信起了关键作用.


4)服务端实现一个继承与service 的类 ,响应客户端的信息

5)重要一步: 清单文件中 注册service

   二.步骤2:写客户端相关代码

1)新建AIDLClient项目 ,将AIDLTest.aidl文件考入相同的package下,必须与服务端包名相同路径下.如下图所示;

    

   2) 在MAinActivity中绑定服务,bindService()

   以下是全部代码

package com.example.aidlclicent;import com.example.aidl_serer.AIDLTest;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Toast;public class MainActivity extends Activity {AIDLTest aidlTest;ServiceConnection con = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName arg0) {// TODO Auto-generated method stubSystem.out.println("MainActivity.send(...).new ServiceConnection() {...}.onServiceDisconnected()");}@Overridepublic void onServiceConnected(ComponentName arg0, IBinder arg1) {// TODO Auto-generated method stubaidlTest = AIDLTest.Stub.asInterface(arg1); // 将ibinder 转换成自定义接口}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}/** * 绑定服务 *  * @param v */public void bind(View v) {//startsebindService(new Intent("ditest"), con, 1);}public void send(View view) {try {String server_give = aidlTest.hi("小明");System.out.println(server_give);} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();Toast.makeText(MainActivity.this, "出错!!", 0).show();}}public void unbind(View view) {if (aidlTest != null)unbindService(con);}}
模拟器3个按钮,绑定服务,发送数据,解绑服务

    接下可以测试了,先运行AIDL_Server 启动服务端,再运行AIDLClient 客户端:

1.点击bind .输出如下日志

       2.点击发送数据,服务响应了我们之前在服务端定义的数据格式:

点击       解绑,调用了 两个方法

      3.再点击发送数据,发现还是能接收服务端返回的数据,这说明解绑之后服务还是继续在运行,实测1小时内我再次点击发送数据还是没有被系统停止.

  


0 0
原创粉丝点击