AIDL服务: 跨进程访问的服务
实现步骤:
1.新建一个IMyService.aidl文件,写入内容
1.2 接口中包含自定义对象,另外还需要建2个文件: 一个实现Parcelable接口的Product类, 一个单独的Product.aidl,并用关键字parcelable修饰
parcelable Product; //这个parcelable关键字声明,类似public
为什么要用Parcelable类,因为要跨进程访问,跨进程访问不能向同一进程访问一样,直接传递位置,必须流化再传递。
参照
http://developer.android.com/guide/components/aidl.html
Passing Objects over IPC
If you have a class that you would like to send from one process to another through an IPC interface, you can do that. However, you must ensure that the code for your class is available to the other side of the IPC channel and your class must support the Parcelable
interface. Supporting the Parcelable
interface is important because it allows the Android system to decompose objects into primitives that can be marshalled across processes.
To create a class that supports the Parcelable
protocol, you must do the following:
- Make your class implement the
Parcelable
interface. - Implement
writeToParcel
, which takes the current state of the object and writes it to aParcel
. - Add a static field called
CREATOR
to your class which is an object implementing theParcelable.Creator
interface. - Finally, create an
.aidl
file that declares your parcelable class (as shown for theRect.aidl
file, below).If you are using a custom build process, do not add the
.aidl
file to your build. Similar to a header file in the C language, this.aidl
file isn't compiled.
AIDL uses these methods and fields in the code it generates to marshall and unmarshall your objects.
For example, here is a Rect.aidl
file to create a Rect
class that's parcelable:
package android.graphics; // Declare Rect so AIDL can find it and knows that it implements // the parcelable protocol. parcelable Rect;
4.manifest中注册服务,并定义action
5.新建一个Android Project,做客户端用
把服务器中自动生成的IMyService.java所在的包整个复制到客户端src中
另外Product.java也要拷贝过去
6.客户端中,声明ServiceConnection,获取IMyService对象
7.客户端绑定服务器的服务
8.调用
总结: 我犯的纠结的错误:
错误: 同一个进程中可以访问,但是跨进程访问时,找不到service
原因:
1 应用与应用之间包名不能相同(可以加上项目名称,用以区分不同项目)
如 com.dhy.testaidl.server.ui
com.dhy.testaidl.client.ui
(拷贝过去的不用管)
2 运行客户端之前要运行服务器,这个居然搞错,我也不懂我怎么想的了