AIDL

在接口文件AIDLFunctions.aidl中,我们定义一个方法 show

interface AidlFunctions{
    void show();
}
服务端:
AIDL的使用,需要一个Service配合,所以我们在服务端还要声明一个Service

public class AIDLService extends Service {
//stub就是系统自动产生的
    AidlFunctions.Stub binder;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        binder = new AidlFunctions.Stub() {

            @Override
            //这里是我们在接口中声明的方法的实现
            public void show() throws RemoteException {
                // TODO Auto-generated method stub
                System.out.println("--------------------收到----------------------");
            }
        };
        return binder;
    }  
}
在AndroidManifest声明Service

        <service android:name="com.example.androidaidl.AIDLService">
            <intent-filter>
                <action android:name="com.example.androidaidl.AIDLService" />
            </intent-filter>
        </service>
客户端:

//绑定服务,要用到ServiceConnection
private ServiceConnection serviceConnection;
//自定义的接口,和服务端一样
private AidlFunctions aidlFunctions;

serviceConnection = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub
        System.out.println("--------------------ServiceDisconnected----------------------");
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // TODO Auto-generated method stub
        System.out.println("--------------------ServiceConnected----------------------");
        aidlFunctions = AidlFunctions.Stub.asInterface(service);
    }
};
Intent intent = new Intent("com.example.androidaidl.AIDLService");
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
//调用show方法
try {
    aidlFunctions.show();
} catch (RemoteException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

猜你喜欢

转载自sunj.iteye.com/blog/2377761