AIDL的学习

来源:互联网 发布:centos 7 64位安装盘 编辑:程序博客网 时间:2024/06/05 03:57

跨应用利用service通信

首先建立2应用,一个拥有service的应用app1,一个作为调用service的应用app2。
在app1中新建一个AIDL文件,这个是个接口,所以可以在里面定义你需要的方法,例如获取数据,设置数据等操作。
interface IMyAidlInterface {    /**     * Demonstrates some basic types that you can use as parameters     * and return values in AIDL.     */    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,            double aDouble, String aString);            void setData(String str);//这是我定义的设置数据方法}
把app1中service类中onBind方法的返回设为 new IMyAidlInterface.stub();由于是接口,所以要实现里面的方法。
 return new IMyAidlInterface.Stub() {            @Override            public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {            }            @Override            public void setData(String str) throws RemoteException {                content = str;//外部通信的内容            }        };

在app2中新建一个Folder里面的AIDL Folder,之后把app1中的AIDL复制进去,连同AIDL的包一起。

同时在app2中启动的服务就得是app1的服务了。
 service = new Intent(); service.setComponent(new ComponentName("app1的包名", ".app1的服务名"));// 例如("com.exm.myapplication","com.exm.myapplication.MyService")

在app2的onServiceConnected方法内实现AIDL
private IMyAidlInterface aidlInterface;    @Override    public void onServiceConnected(ComponentName name, IBinder service) {        aidlInterface= IMyAidlInterface.Stub.asInterface(service);//        MyService.MyBinder binder = (MyService.MyBinder) service;////        binder.setdata("QAQ");//        binder.getservice().setCallback(new MyService.callback() {////            @Override//            public void getdata(String str) {//                text = str;//                handler.sendEmptyMessage(0);//            }//        });        Log.d(TAG, "onServiceConnected");    }
最后,在需要的地方调用
aidlInterface.setData("你的通信内容");
就能实现app2向app1通过service发送信息了。
注意:当然你得先绑定app1的service。


第一次记录,感觉很乱。
0 0
原创粉丝点击