IPC进程通信机制---------AIDL实战

来源:互联网 发布:多益网络实力 编辑:程序博客网 时间:2024/06/07 17:20
本篇带你揭开AIDL神秘的面纱:相似知识点:Service通信。

IPC,含义为进程间通信或则跨进程通信,是指两个进程之间进行数据交换的过程。

AIDL: Android interface defination language.

适应读者:熟悉Service通信。

Start:
三点关键点:
1、服务端, Service。
2、客户端,Activity。
3、AIDL接口的创建。


第一点:

public class AIDLService extends Service {    private final String INFO = "我是另外一个进程的数据信息哦";    @Override    public void onCreate() {        super.onCreate();    }    @Nullable    @Override    public IBinder onBind(Intent intent) {        return mBinder;    }    private Binder mBinder = new IMyAidlInterface.Stub(){        @Override        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {        }        @Override        public String getInfo() throws RemoteException {            return INFO;        }    };}


并且在xml文件中,定义Service。



第二点:绑定Service。

/** * ServiceConnection 进程间通信的桥梁。 */ServiceConnection serviceConnection = new ServiceConnection() {    @Override    public void onServiceConnected(ComponentName name, IBinder service) {        IMyAidlInterface inter = IMyAidlInterface.Stub.asInterface(service);        try {            Log.e("MainActivity", "==========================" + inter.getInfo());        } catch (RemoteException e) {            e.printStackTrace();        }    }    @Override    public void onServiceDisconnected(ComponentName name) {    }};@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    Intent intent = new Intent(this, AIDLService.class);    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);}





第三点:定义AIDL接口。

interface IMyAidlInterface {    /**     * Demonstrates some basic types that you can use as parameters     * and return values in AIDL.     */    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,            double aDouble, String aString);    String getInfo();}


补充:
【定义形式,如Java接口定义形式】
【特殊注意:AIDL默认支持,基本类型、String、List、Map类型对象,如果需要传递其他引用类型对象,请查看下一篇文章介绍,本篇秉着简单易懂的形式,带你通过AIDL实现IPC机制。】
【特殊注意:当编写完AIDL接口,在AndroidStudio中,你需要手动Build 当前项目,否则,编译器查询不到.aidl文件。。】









原创粉丝点击