【android,15】aidl

来源:互联网 发布:python scatter 气泡 编辑:程序博客网 时间:2024/04/20 07:00

一、aidl简介:

aidl :android interfacedefination language (android 接口定义语言)

用于:调用远程服务(另外一个进程里面的服务的方法)。

二、通过aidl调用另外一个进程的服务的方法:

1、定义一个IService.aidl 文件 :内容为:

 interface IService {

   void callMethodA();

}

系统会将文件解析成一个IService.java文件放在gen目录下:

IService.java内容是:

public interface IService extends android.os.IInterface{

    publicstatic abstract class Stub extends android.os.Binder

implementscn.itcast.remoteservice.IService{

    }

}

解析为IService接口继承IInterface类,并定义一个内部抽象类IService.Stub类继承android.os.Binder类,实现IService接口 ,

 

2、①、定义一个服务类:内部有个Binder的子类:

public class MyService extends Service {

//Binder的子类

    public class MyBinder extendsIService.Stub{

 

        @Override

        public void callMethodA() {

            //调用服务的方法

            MethodA();

        }

       

    }

   

    @Override

    public IBinder onBind(Intentintent) {

        // TODO Auto-generated method stub

        System.out.println("onbind");

        return new MyBinder();

    }

 

    public void MethodA(){

        System.out.println("我是远程服务里面的方法A");

    }

 

}

②、在清单文件中声明service组件:

<application

       android:icon="@drawable/ic_launcher"

        android:label="@string/app_name">

        <serviceandroid:name=".MyService">

            <intent-filter >

                <actionandroid:name="cn.itcast.remoteservice"/>

            </intent-filter>

        </service>

    </application>

 

 

3、在另外程序中绑定上面的服务:获取binder子类对象 调用服务组件中的方法

首先将写好的IService.aidl拷贝到该程序中,(保持包名相同),在工程的gen目录下也会生成遇上面内容相同的IService.java文件。

 

//使用隐式意图获取前一个程序中的service组件

Intent service = new Intent();

service.setAction("cn.itcast.remoteservice");

//绑定service

bindService(service, new Myconn(),BIND_AUTO_CREATE);

      

// ServiceConnection子类:

private class Myconn implements ServiceConnection{

 

        @Override

     publicvoid onServiceConnected(ComponentNamename, IBinder service) {

            System.out.println("远程服务绑定成功了");

//获取IService接口的实现类:

//调用asInterface()方法:参数为service对象

            IService iservice =IService.Stub.asInterface(service);

        }

 

        @Override

        public void onServiceDisconnected(ComponentName name) {

           

        }

    }

   

    public voidcallMethod(View view){

    try {

//调用接口中的方法:

            iservice.callMethodA();

        } catch(RemoteException e) {

            // TODOAuto-generated catch block

            e.printStackTrace();

        }

    }

 

 

三、使用aidl 挂断电话:

 

 

0 0
原创粉丝点击