为什么 AIDL 接口客户端、服务端要写两份一模一样的?

一、核心一句话(必背)

因为 AIDL 是跨进程通信,客户端和服务端属于两个独立的进程,内存不共享。两边必须有 完全相同的接口文件(包名 + 文件名 + 内容一致) ,才能生成 一模一样的通信协议代码 ,实现跨进程 "说同一种语言"。


二、通俗大白话解释

你把 AIDL 接口 想象成 "翻译官手册"

  • 客户端是外国人
  • 服务端是中国人
  • 两个进程 = 两个国家,语言不通、内存不互通

要交流必须:两边拿着【一模一样】的翻译手册!

  • 客户端靠这个 AIDL 把请求翻译成序列化数据
  • 服务端靠这个 AIDL 把数据翻译回方法调用

如果两边不一样 → 翻译对不上 → 通信直接报错!


三、真正的技术原因

  1. AIDL 会自动生成 Java 代码(Stub、Proxy)客户端和服务端依赖的自动生成类必须完全一致。
  2. 跨进程传输需要 唯一标识(descriptor)**AIDL 会生成一个唯一的字符串标识:interface-Descriptor两边不一样,系统会认为不是同一个接口,直接拒绝通信
  3. 进程间内存独立 客户端和服务端是两个独立 APK / 独立进程,不共享代码,所以必须各放一份。

四、最重要的关键点(面试官必问)

必须一模一样的是哪 3 点?

  1. 包名完全一样
  2. 文件名完全一样
  3. 接口内容完全一样

只要有一个不一样,直接报错,无法绑定


五、30 秒面试背诵版(直接背)

因为客户端和服务端属于两个不同进程,内存不共享 ,AIDL 是跨进程通信的协议接口 。两边必须拥有包名、文件名、内容完全相同 的 AIDL 文件,才能生成一致的通信代码和唯一描述符,确保跨进程数据能正确序列化和反序列化。否则无法识别对方,通信失败。


六、面试官延伸问题

问:能不能只写一份,让两边依赖?

答:可以!实际项目不会写两份,而是抽成一个独立的 AIDL 模块(library) ,客户端和服务端共同依赖这个库。但原理不变:最终两边还是拥有完全相同的 AIDL 结构。

7、客户端代码:

gitee地址:gitee.com/lyyon/aidlT...

1、IMyAidlInterface

arduino 复制代码
// IMyAidlInterface.aidl
package com.example.aidlservice;

// 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.
     */
    String getStringFromService();

     void sendMessage(String msg);
}
注意:写完之后,等待编译。

2、MainActivity

java 复制代码
package com.example.aidlclient;

import androidx.appcompat.app.AppCompatActivity;

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.widget.TextView;

import com.example.aidlservice.IMyAidlInterface;

public class MainActivity extends AppCompatActivity {

    private IMyAidlInterface myAidlInterface = null;
    private TextView txt = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt = findViewById(R.id.txt);

        ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                myAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
                try {
                    String s = myAidlInterface.getStringFromService();
                    txt.setText(s);
                    myAidlInterface.sendMessage("客户端发送消息:Hello world");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };

        Intent intent = new Intent();
        intent.setAction("com.example.service.action");
        intent.setPackage("com.example.aidlservice");
        bindService(intent,connection,BIND_AUTO_CREATE);
    }
}

3、activity_main.xml

ini 复制代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txt"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

8、服务端代码:

1、IMyAidlInterface

arduino 复制代码
// IMyAidlInterface.aidl
package com.example.aidlservice;

// 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.
     */
    String getStringFromService();

     void sendMessage(String msg);
}
注意:写完之后,等待编译。

2、MyService

scala 复制代码
package com.example.aidlservice;

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

public class MyService extends Service {
    private static final String TAG = "---MyService---";
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new Mybinder();
    }

    class Mybinder extends IMyAidlInterface.Stub{
        @Override
        public String getStringFromService() throws RemoteException {
            Log.d(TAG, "service 端的方法被client调用了");
            return "88888888";
        }

        @Override
        public void sendMessage(String msg) throws RemoteException {
            Log.d(TAG, "msg: "+msg);
        }
    }
}

3、manifest

ini 复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.aidlservice">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AidlTest">
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
            <intent-filter >
                <action android:name="com.example.service.action"/>
            </intent-filter>
        </service>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
相关推荐
weiggle6 小时前
第一篇:Jetpack Compose 宣言——为什么 Android 开发需要声明式 UI
android
城管不管8 小时前
什么是Prompt?
android·java·数据库·语言模型·llm·prompt
weiggle8 小时前
Jetpack Compose 重组机制与性能优化深度剖析
android
●VON9 小时前
鸿蒙Flutter实战:24小时新建标签提示组件
android·flutter·华为·harmonyos·鸿蒙
2501_916007479 小时前
iOS应用性能优化全面指南:从内存管理到工具使用
android·ios·性能优化·小程序·uni-app·iphone·webview
程序员陆业聪9 小时前
WebView代理方案实现:拦截请求、注入资源与离线包架构
android
好好风格10 小时前
把一台 Root 安卓机交给 AI 智能体,会发生什么?
android·人工智能·开源
赏金术士11 小时前
企业级 Jetpack Compose 项目(入门版)最佳结构
android·kotlin·compose