Android 跨进程通信 Aidl 的使用及注意事项

2,178 阅读2分钟
原文链接: mp.weixin.qq.com
1前提

    在其他进程开辟使用内存,不会影响当前App进程;进而,也会很大一部分避免App被垃圾回收机制回收;

QQ的网路通信使用的就是跨进程通讯。

2创建Aidl接口文件

    创建一个File,命名为:xxx.aidl;此处命名为:IIncrementUpdateServer.aidl,具体请看下图aidl文件所在位置:

查看图片

创建完成后,如下所示:

查看图片

IIncrementUpdateServer.aidl内容定义如下:

查看图片

//此方法是创建aidl自带的方法,告知你可以使用那些数据类型

 void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,

            double aDouble, String aString);

自定义的aidl接口,根据情况,定义跨进程所需接口:

void start();

void reload();

void stop();

3 创建服务Service

创建service,此处命名为:IIncrementUpdateService,继承于Service,具体如下:

查看图片

查看图片

注意:

onBind方法中,通过new实例化了一个IncreamentUpdateImpl实例对象,和Service进行绑定;IncreamentUpdateImpl继承于IIncrementUpdateServer.Stub;当然,你也可以直接实例化IIncrementUpdateServer.Stub进行绑定;

在AndroidManifest.xml中静态申明Service,如下:

查看图片

注意:

action定义为:cn.coolspan.IncrementUpdateService,需和调用之处一致。

到此,Aidl与Service都定义完成;接着,就是如何使用。

4 使用方式

我是在Activity中进行调用的,如下:

首先,创建ServiceConnection获取到Service:

查看图片

然后,绑定Service:

查看图片

解除绑定:

查看图片

最后调用:

mService.start();

结果,就会输入Service中的Log信息。

connect service

start

5 注意事项

1、如果在onCreate中进行bindService,在Destroy中unBindService,当Activity暂停的时候就会出现以下异常信息

 Activity cn.coolspan.open.android_increment_update.MainActivity has leaked ServiceConnection cn.coolspan.open.android_increment_update.MainActivity$1@421de608 that was originally bound here

                                                                                           android.app.ServiceConnectionLeaked: Activity cn.coolspan.open.android_increment_update.MainActivity has leaked ServiceConnection cn.coolspan.open.android_increment_update.MainActivity$1@421de608 that was originally bound here

我的解决方法:

>把bindService放到onResume中,unBindService放在onPause中;


2、java.lang.IllegalArgumentException: Service Intent must be explicit: Intent {act=cn.coolspan.IncrementUpdateService (has extras) }

解决方法:在onResume方法中的注释部分以解决,对Intent设置package

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {

    intent.setPackage("cn.coolspan.open.android_increment_update");

}

暂时就遇到这2个坑,如果其他的问题,我会陆续更新到此文章中;

文章出处:

[Coolspan CSDN博客:http://blog.csdn.net/qxs965266509]

欢迎关注我的公众号,实时给你推送文章,谢谢支持; 

微信搜索公众号:**coolspan**

文章出自:Coolspan,欢迎大家关注公众号查看原文。

查看图片查看图片