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

来源:互联网 发布:电冰箱直播软件 编辑:程序博客网 时间:2024/06/06 20:58

跨应用绑定 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 binded10-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 default10-21 11:20:34.681 25488-25530/com.jackie.startanotherapp V/jackie: data is default10-21 11:20:36.681 25488-25530/com.jackie.startanotherapp V/jackie: data is default10-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通信了。

0 0
原创粉丝点击