进程间通信Aidl的简单案例

本文提供了一个简单的 Android AIDL (Android Interface Definition Language) 示例,通过服务端与客户端的交互演示了如何使用 AIDL 进行进程间通信。示例包括了 ICat.aidl 文件定义、服务端 AidlService 的实现及客户端的调用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  最近,在学习Android进程间通信,发现用的比较多的是aidl,想在网上找点demo来看一下,但是我找了很久,没找到我觉得满意的代码,要么是文字写的太含蓄了看不懂,要么是代码长的看不进去,其实我就是想找个demo运行一下,看一看效果再来分析其中aidl的原理,于是就自己敲了一个demo,仅供参考,如下:

首先是写服务端代码:

ICat.aidl代码:


packagestartimes.com.aidlservice;

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

interface ICat {
    String getColor();
    double getWeight();
}

AidlService.java代码:

public class AidlService extends Service {
   private CatBinder catBinder;
    Timer timer=new Timer();
    String[] colors=new String[]{"红色","黄色","黑色"};
    double[] weights=new double[]{2.3,3.1,1.58};
    private String color;
    private double weight;
 //继承Stub,也就是实现了ICat接口,并实现了IBinder接口
    public class CatBinder extends ICat.Stub
    {
     @Override
      public String getColor() throws RemoteException {
        return color;
      }
     @Override
      public double getWeight() throws RemoteException {
        return weight;
      }
    }
     @Override
  public void onCreate() {
    super.onCreate();
    catBinder=new CatBinder();
    timer.schedule(new TimerTask(){
      @Override
      public void run() {
        //随机地改变Service组件内color,weight属性的值
        int rand= (int) (Math.random()*3);
        color=colors[rand];
        weight=weights[rand];
        System.out.println("--------"+rand);
      }
    },0,800);
  }

  @Nullable
    @Override
    public IBinder onBind(Intent intent) {
      //返回catBinder对象,在绑定本地Service的情况下,该catBinder
    //对象会直接传给客户端的ServiceConnection对象的onServiceConnected
    //方法的第二个参数;在绑定远程Service的情况下,只将catBinder对象的代理
    //传给客户端的ServiceConnection对象的onServiceConnected方法的第二个参数;
        return catBinder;
    }

  @Override
  public void onDestroy() {
    timer.cancel();
  }
}
MainActivity.java中代码:
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

AndroidManifest.xml中添加:
<service
    android:name=".AidlService"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="startimes.com.aidlservice.Aidl_Service"/>
    </intent-filter>
</service>

运行一下看一看。

然后将服务端aidl文件夹拷到客户端中,客户端代码:


public class AidlClient extends Activity {
    private ICat catService;
    private Button get;
    EditText color,weight;
    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //获取远程ServiceonBind方法返回的对象代理
            catService=ICat.Stub.asInterface(iBinder);

            get.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        //获取,并显示远程Service的状态
                        color.setText(catService.getColor());
                        Toast.makeText(AidlClient.this,catService.getColor()+"",Toast.LENGTH_LONG).show();
                        weight.setText(catService.getWeight()+"");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            catService=null;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aidl_client);
        get= (Button) findViewById(R.id.get);
        color= (EditText) findViewById(R.id.color);
        weight= (EditText) findViewById(R.id.weight);
        //创建所需绑定服务的Intent
        Intent intent = new Intent();
        intent.setAction("startimes.com.aidlservice.Aidl_Service");
        //绑定远程服务
        bindService(intent,conn, Service.BIND_AUTO_CREATE);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除绑定
        this.unbindService(conn);
    }
}
布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
   >
<Button
    android:id="@+id/get"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="获取远程服务"
    />
   <EditText
       android:id="@+id/color"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="颜色"
       />
   <EditText
       android:id="@+id/weight"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="权重"
       />
</LinearLayout>
注意:先运行服务端代码,会退后,在运行客户端代码,效果

服务端:


客户端:


代码链接:https://github.com/HotBloodMan/CommonCode/blob/master/AIDLdemo.zip

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值