Android中关于AIDL的应用

本文详细介绍了Android接口定义语言(AIDL)的概念及其在Android应用中的使用方式,包括创建.aidl文件、实现Service中的onBind方法及Activity中的ServiceConnection等关键步骤。

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

首先解释一下什么是AIDL

AIDL就是Android Interface Defind Language 安卓接口定义语言。

在Android中的主要作用是跨进程通信。

1.首先要使用AIDL必须要有.aidl文件,里面定义的是一些接口。

2.如果.aidl文件没有错误,将会在gen包下生成这个.audl文件的.java文件

       a.生成的.Java文件是一个接口,这个接口会继承android.os.Interface这个类

b.在这个接口中会自动生成一个Stub的抽象类,这个类继承了android.os.Binder这个类,实现了我们aidl文件接口

3.实现aidl文件中的内部抽象类Stub

4.实现service中的onBinder方法

5. 在要绑定到该Service的Activity中 创建ServiceConnection对象的onServiceConnected方法中调用 AIDL接口.Stub

    的asInterface(binder)将绑定后返回的binder对象转换为AIDL接口对象


首先在我们的工程中创建一个自定义的.aidl文件。

这里我写的代码如下:

package com.example.aidl;
interface MyAIDL{
void onCreate();
void onStart();
void onStop();
}

 然后在Service中的代码:

package com.example.service;


import com.example.aidl.MyAIDL;


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


public class MyService extends Service {
public class MyBinder extends MyAIDL.Stub{


@Override
public void onCreate() throws RemoteException {
// TODO Auto-generated method stub

}


@Override
public void onStart() throws RemoteException {
// TODO Auto-generated method stub

}


@Override
public void onStop() throws RemoteException {
// TODO Auto-generated method stub

}


}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}


}

测试我们的跨进程:


在activity中的代码如下:

package com.example.test_aidl_activity;


import com.example.aidl.MyAIDL;


import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;


public class MainActivity extends Activity {

private MyAIDL my_aidl;
ServiceConnection sconn = new ServiceConnection() {

@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub

}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
my_aidl = MyAIDL.Stub.asInterface(service);
}
};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent("com.example.action.BIND_SERVICE"); 
        bindService(intent, sconn, BIND_AUTO_CREATE);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值