日报2015/10/21(极客学院安卓视频学习)

本文详细阐述了如何在Android应用间通过创建AIDL并实现远程Service通信的方法,包括服务绑定、通信实例化及异常处理等关键步骤。

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

跨应用绑定 Service 并通信

直接右键项目新建一个AIDL,在service的onBind(Intent intent) 里面返回new IMyAidlInterface.Stub()

    @Override
    public IBinder onBind(Intent intent) {

        return new IMyAidlInterface.Stub() {
            @Override
            public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

            }
        };
    }

仍然用之前的

        serviceIntent = new Intent();
        serviceIntent.setComponent(new ComponentName("com.jackie.startanotherapp",
                "com.jackie.startanotherapp.AppService"));
//绑定服务的代码
bindService(serviceIntent, this, Context.BIND_AUTO_CREATE);
//解绑服务的代码
unbindService(this);

而在绑定服务的时候,获取一下IBinder对象:

10-21 10:42:53.371 30813-30813/com.jackie.anotherapp V/jackie: Service binded
10-21 10:42:53.371 30813-30813/com.jackie.anotherapp V/jacke: Ibinder is android.os.BinderProxy@42a63810

跨应用绑定 Service 并通信

绑定服务的目的就在于与服务进行通信,只绑定不实现通信是毫无意义的。

之前学过的通信的时候,是自己定义一个MyBinder,然后在里面进行数据的修改,这里既然有了AIDL,就在它里面添加抽象方法即可。

如果要实现远程通信,那么在anotherapp里面要新建一个aidl folder,里面新建包,包名要和service所在包一样,而且将aidl拷贝进去
这里写图片描述

这样一来,anotherapp也可以找到IMyAidlInterface的定义了,在它的MainActivity里面定义

private IMyAidlInterface binder;
...
//修改data
            case R.id.sync:
                try {
                    binder.setData(editText.getText().toString());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

如果运行出现NullPointerException,那么很可能是忘记在onServiceConnected(ComponentName name, IBinder service) 里面给binder初始化一下:

binder = (IMyAidlInterface) service;

然而po主修改以后发现虽然绑定以后线程运行了但是anotherapp报错了,

java.lang.ClassCastException: android.os.BinderProxy cannot be cast to com.jackie.startanotherapp.IMyAidlInterface

因为两个aidl的内存是不一样的

//binder = (IMyAidlInterface) service;
binder = IMyAidlInterface.Stub.asInterface(service);

要这样写才行

然后观察logcat

10-21 11:20:32.681 25488-25530/com.jackie.startanotherapp V/jackie: data is default
10-21 11:20:34.681 25488-25530/com.jackie.startanotherapp V/jackie: data is default
10-21 11:20:36.681 25488-25530/com.jackie.startanotherapp V/jackie: data is default
10-21 11:20:38.681 25488-25530/com.jackie.startanotherapp V/jackie: data is 修改后
10-21 11:20:40.681 25488-25530/com.jackie.startanotherapp V/jackie: data is 修改后
10-21 11:20:42.681 25488-25530/com.jackie.startanotherapp V/jackie: data is 修改后

这样就实现了跨应用远程service通信了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值