使用ADIL访问远程服务

1.新建aidl文件


2.Build->Make Project

在该目录下可以发现生成后的IMyAidlInterface.java文件。


3.新建Service并实现IMyAidlInterface定义的方法,onBind中返回实例。

public class MyRemoteService extends Service {

    public MyRemoteService() {
    }

    IMyAidlInterface.Stub myAidlInterface = new IMyAidlInterface.Stub() {
        @Override
        public String SayHello(String world) throws RemoteException {
            return world;
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return myAidlInterface;
    }
}
4.Manifest 中修改定义

<service
    android:name=".MyRemoteService"
    android:enabled="true"
    android:exported="true"
    android:process=":remote"
    >
    <intent-filter>
    <action android:name="my.test.com.servicedemo.MyService" />
</intent-filter>
</service>
5.Activity中调用

楼主下午一直报null因为在bindService后直接调用myAidlInterface 的方法了,此时应该并没有执行完onServiceConnected,

所以最好在onServiceConnected后再调用方法!

intent_aidl = new Intent(this, MyRemoteService.class);
bindService(intent_aidl, aidl_ServiceConnection, BIND_AUTO_CREATE);
private IMyAidlInterface myAidlInterface = null;
ServiceConnection aidl_ServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        Log.i("MainActivity", "ComponentName:"+componentName);
        myAidlInterface = (IMyAidlInterface.Stub.asInterface(iBinder)) ;
        if(myAidlInterface==null)
        Log.i("MainActivity", "myAidlInterface==null");
        else
        {
            try {
                String temp=myAidlInterface.SayHello("fuck uuuuuuu!!!!!!");
                Toast.makeText(MainActivity.this,temp,Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }


    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值