AIDL快速入门

【原文】蛇发女妖 的博客地址:

http://www.jianshu.com/users/d2aa06a908d5

“Android进程通信”,乍一听感觉好深奥的东西。到底什么是进程通信呢?举个栗子:现在我手机有两个应用程序,其中一个我们暂且叫它客户端,它的功能是实现两个数相加,即当你在界面中输入两个数,点一下计算的按钮,就会得到两个数相加的结果。第二个应用程序我们暂且叫它服务端,它是用来存放客户端的具体逻辑的,即两个数相加的具体计算过程在这个应用程序中。我们在客户端中输入两个数,然后将这两个数传到服务端中,服务端经过计算把两个数的相加结果再传回客户端。这样两个应用程序便实现了通信。

Android实现进程间的通信有四种方式,分别对应于Android中的四大组件。即Activity、Broadcast、ContentProvider、Service。其中Activity可以通过Intent访问其他进程的Activity,Broadcast可以给Android系统中所有的应用程序发送广播,需要跨进程通信的应用程序可以监听这些广播,ContentProvider可以向其他应用程序共享数据,以及允许其他应用程序对其数据进行增删改查操作。最后便是本文的重点,通过Service利用AIDL进行通信。

AIDL(Android Interface Definition Language)是一种接口定义语言,由于Android的每个进程都运行在独立的虚拟机中,所以进程之间通信会比较麻烦。我们可以利用AIDL将一个进程的数据拆分成Android系统可识别的数据单元,然后系统再重新将数据单元合成传递给另一个进程。这样就实现了进程间的通信。


那么我们该如何使用AIDL呢?既然AIDL是一种接口定义语言,自然我们就得先定义好接口。具体的步骤如下:

1.创建.aidl文件
2.实现接口
3.将接口暴露给客户端

接下来我们来通过本文开头这个例子来具体讲讲如何通过以上三步就可以实现进程间的通信。

第一步:创建.aidl文件

如上图,新建一个Android工程,然后添加一个模块。其中一个aidlclient作为客户端,另一个app为服务端。先在app文件夹下建立一个与Java文件同级的文件夹命名为“aidl”,再在这个文件夹下新建一个与该模块同名的包,包下新建一个aidl接口。注意其扩展名为aidl。在该文件中我们便可以定义自己的接口,在上例中我们可以这样定义:

package com.example.administrator.aidldemo;
interface IMyAidlInterface { 
  int add(int num1,int num2);
}

注:文件必须声明包名,且要和该服务端模块的包名相同。接口方法中的入参支持基本数据类型,除short外。因为其无法被序列化

然后我们在客户端aidlclient模块下新建一个与服务端中一模一样的aidl文件夹,注意客户端中的aidl文件夹下的内容必须保证和服务端的一致,包括包名和具体的aidl文件。
然后我们编译一下Android Studio,在两个模块的
build-->generated-->source下生成一个aidl文件夹,且文件夹下的目录如下图所示则表示我们的aidl文件已经创建成功


第二步:实现接口

在我们的服务端的模块的Java文件夹下新建一个服务如下图:


该服务类中的代码如下

package com.example.administrator.aidldemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
public class IRemoteService extends Service {
    @Nullable    
    @Override    
    public IBinder onBind(Intent intent) { 
         return iBinder;    
    }    
   private IBinder iBinder = new IMyAidlInterface.Stub(){        
       @Override        
       public int add(int num1, int num2) throws RemoteException {
            return num1+num2;        
       }    
   };
}

其中如下代码,我们通过调用编译生成的IMyAidlInterface的Stub方法实现我们之前定义的接口,即完成了我们的第二步实现接口

private IBinder iBinder = new IMyAidlInterface.Stub(){
  @Override 
  public int add(int num1, int num2) throws RemoteException {
   return num1+num2; 
  } 
};

注:别忘了在AndroidManifest文件中注册该Service

<service android:name=".IRemoteService"    
 android:process=":remote"   
 android:exported="true">
</service>
第三步:将接口暴露给客户端
public IBinder onBind(Intent intent) {
 return iBinder; 
}

我们只要在IRomoteService中的onBind中返回我们实现好的接口。这样一旦客户端绑定该服务就会执行onBind方法从而得到已实现好的接口。客户端得到该接口就可以调用接口中的add方法来实现加法的运算。
接下来我们来看一下调用的具体过程:
首先我们将客户端的界面先布置好:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:orientation="vertical">    
<EditText        
android:gravity="center|right"        
android:id="@+id/et_num1"        
android:layout_width="match_parent"        
android:layout_height="wrap_content" />    
<TextView        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:text="+"        
android:textSize="24sp"        
android:layout_gravity="center"        
android:gravity="right|center"/>    
<EditText        
android:gravity="center|right"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:id="@+id/et_num2"/>    
<TextView        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:text="="        
android:textSize="24sp"        
android:layout_gravity="center"        
android:gravity="right|center"/>    
<EditText        
android:gravity="center|right"        
android:editable="false"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:id="@+id/edit_show_result"        
android:textSize="24sp"/>    
<Button        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:id="@+id/btn_count"        
android:text="远程计算"        
android:gravity="center"        
android:textSize="24sp" />
</LinearLayout>

界面非常简单在两个EditText中输入两个数点击按钮,然后显示计算结果。

接下来我们来看一下该界面的具体Java代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_num1;
    private EditText et_num2;
    private EditText edit_show_result;
    private Button btn_count;
    private int mNum1;
    private int mNum2;
    private int mTotal;
    private IMyAidlInterface iMyAidlInterface;
    //绑定服务回调
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //服务绑定成功后调用,获取服务端的接口,这里的service就是服务端onBind返
            //回的iBinder即已实现的接口
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            //解除绑定时调用,清空接口,防止内容溢出        
            iMyAidlInterface = null;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.activity_main);    
        bindService();   
        initView();
    }
    //初始化界面
    private void initView(){
        et_num1 = (EditText)findViewById(R.id.et_num1);    
        et_num2 = (EditText)findViewById(R.id.et_num2);    
        edit_show_result = (EditText)findViewById(R.id.edit_show_result);    
        btn_count = (Button)findViewById(R.id.btn_count);        
        btn_count.setOnClickListener(this);
    }
    //按钮点击事件
    private void handleBtnClickEvent(){
        mNum1 = Integer.parseInt(et_num1.getText().toString());    
        mNum2 = Integer.parseInt(et_num2.getText().toString());    
        try {        
            mTotal = iMyAidlInterface.add(mNum1,mNum2);    
        } catch (RemoteException e) { 
           e.printStackTrace();    
        }    
        edit_show_result.setText(mTotal+"");
    }
    //绑定服务
    private void bindService(){  
        Intent intent = new Intent();    
        intent.setComponent(newComponentName("com.example.administrator.aidldemo",  
          "com.example.administrator.aidldemo.IRemoteService"));   
        bindService(intent,conn, Context.BIND_AUTO_CREATE);
    }
    @Override
    public void onClick(View v) { 
       handleBtnClickEvent();   
     }    
    protected void onDestroy(){    
        super.onDestroy();
        //当活动销毁时解除绑定        
        unbindService(conn);    
    }
}

其实上面的代码还是很好理解的,当启动客户端,将会执行bindService方法,去绑定服务端的远程服务,一旦绑定成功,就会回调conn 中的onServiceConnected方法。在方法中,我们获取到了服务端实现好的接口。即服务端将该实现好的接口暴漏给了客户端。
然后当我们输入两个数,点击按钮时,就可以调用我们刚得到的接口的add方法,来实现两个加数的相加运算。

这样我们就完成整个例子的编码,接下来我们就来运行下。
先运行服务端的模块,再运行客户端的。


服务端应用程序

客户端应用程序
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值