Android中AIDL的簡單使用
AIDL這里就不加累述它的概念定義等等,免得長篇大幅。下面介紹的是簡單的一次使用AIDL成功與service通信的一個例子:
1.在項目包下新建一個IInfo.aidl,并在其中添加你要調用的方法,格式和java中接口一樣。package com.android.server;
- interface IInfo {
- boolean start();
- void stop();
- void locate(int x, int y);
- void move(int dx, int dy);
- void getLocation(inout int[] p);//參數(shù)為數(shù)組的話,可以加上inout,不然會報錯
- void setTimeout(int t);
- int getTimeout();
- void setBitmap(inout byte[] bmp, int width, int height);}
正確寫好之后,eclipse的adt會自動在gen目錄下生成一個IInfo.java文件
2.新建一個CursorService.java類,繼承IInfo.stub,如下:
- package com.android.server;
- public class CursorService extends ICursorInfo.Stub{
- final boolean hasService;
- public CursorService() {
- hasService = initializeJNI();
- }
- public synchronized boolean start() {
- if (hasService)
- return start0();
- return false;
- }
- public synchronized void stop() {
- if (hasService)
- stop0();
- }
- public synchronized void locate(int x, int y) {
- if (hasService)
- locate0(x, y);
- }
- public synchronized void move(int dx, int dy) {
- if (hasService)
- move0(dx, dy);
- }
- public synchronized void getLocation(int[] p) {
- if (p == null)
- throw new NullPointerException("p is null");
- if (p.length < 2)
- throw new IllegalArgumentException("p.len must >= 2");
- if (hasService)
- getPosition0(p);
- }
- public synchronized void setTimeout(int t) {
- if (hasService)
- setTimeout0(t);
- }
- public synchronized int getTimeout() {
- if (hasService)
- return getTimeout0();
- return -1;
- }
- public void setBitmap(byte[] bmp, int width, int height) {
- if(bmp == null)
- throw new NullPointerException("bmp is null");
- if(width < 0 || height < 0)
- throw new IllegalArgumentException("width < 0 || height < 0");
- if(width * height > bmp.length)
- throw new IndexOutOfBoundsException("bmp less than width*height");
- setBitmap0(bmp,width,height);
- }
在其中實現(xiàn)你aAIDL中的方法
3. 新建一個Manager類,在其中構造一個內部服務連接類,實現(xiàn)ServiceConnection接口:
- public class Manager {
- private static final String TAG = "Manager";
- private IInfo iCurSer;
- private Manager(){
- }
- public Manager(Context ctx){
- this.context = ctx;
- new Manager();
- }
- /**這里就可以與service正常通信,調用service中的方法**/
- public void startService(){
- Intent intent=new Intent("com.android.server.CursorService");
- context.bindService(intent,new CursorServiceConnection(),
- Service.BIND_AUTO_CREATE);
- }
- /**
- * 實現(xiàn)ServiceConnection接口
- * */
- public final class CursorServiceConnection implements ServiceConnection{
- // 和CursorService綁定時系統(tǒng)回調這個方法
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- // 此處不能使用強制轉換, 應該調用Stub類的靜態(tài)方法獲得CursorService接口的實例對象
- iCurSer=ICursorInfo.Stub.asInterface(service);
- }
- //解除和CursorService的綁定時系統(tǒng)回調這個方法
- @Override
- public void onServiceDisconnected(ComponentName name) {
- iCurSer=null;
- }
- }
- }
Android中AIDL的簡單使用就mark到這吧,希望對剛剛學Android的開發(fā)者能有些幫助。