Android AIDL 简单实用

1 什么是AIDL,AIDL是干嘛用的呢? 
  AIDL 是一个内部进程间通信描述语言,于我来理解,它的定义形式是很固定,简单的 

2 AIDL 在什么情况下使用? 
  举个例子,当你的Android APP想调用第三方应用或者你自己写的服务进程,可以使用, 

3 怎么使用呢? 
  
  首先你要先定义好你的AIDL文件 XXX.aidl,很简单,看文件的内容 
  
 

Java代码   收藏代码
  1. interface IAidlService {  
  2. void method();  
  3. }  



   定义一个接口,供外部进程调用 


其次,你需要写一个Service形式如下: 

 

Java代码   收藏代码
  1. public class AidlService extends Service {  
  2.   
  3.    //Stub类继承了IBinder,实现了AIDL定义的接口  
  4.    IBinder mServiceBinder = new IBacklightBrightnessService.Stub() {  
  5.          
  6.        @Override  
  7.        public void method() {  
  8.            //方法的具体实现  
  9.              
  10.        }  
  11.    };  
  12.    
  13.      
  14.    @Override  
  15.    public IBinder onBind(Intent intent) {  
  16.       //返回给调用方binder对象,可调用服务中的接口  
  17.        return mServiceBinder;  
  18.    }  
  19.   
  20.      


   
  从上面看,该服务是不是比较简单,自己理解下吧 


  最后开始调用方的操作了: 
  你必须在你的进程:如在Activity中, 建立到AIDL 服务的连接,形式如下: 

 

Java代码   收藏代码
  1. this.bindService(new Intent("com.example.intent.action"), mServiceConnection, Context.BIND_AUTO_CREATE);  



  具体参数说明 

   new Intent("com.example.intent.action"):启动service 的IntentFilter 
   mServiceConnection:连接服务的桥梁,形式如下: 
   
  

Java代码   收藏代码
  1. private AidlService mAidlService = null;  
  2.      
  3.    private ServiceConnection mServiceConnection = new ServiceConnection() {  
  4.   
  5.        @Override  
  6.        public void onServiceDisconnected(ComponentName name) {  
  7.            // log("onServiceDisconnected");  
  8.        }  
  9.   
  10.        @Override  
  11.        public void onServiceConnected(ComponentName name, IBinder service) {  
  12.            mAidlService = AidlService.Stub.asInterface(service);  
  13.        }  
  14.    };  


    该连接返回服务进程的binder对象,有了它就可以调用服务端接口啦 


   好了,到此,你就基本掌握AIDL的使用了,是不是很简单? 


   题外之延伸: 

   通过这个例子,你有没有想到Service中 startService 和 bindService的区别? 

   注意bind的service销毁了,activity 要解绑否则activity 也会销毁 

   平时大家在使用跨进程的时候,注意方式的选择,跨进程无非是数据的共享,可采用的方法不单单是AIDL,可以如下 

   1  广播Brocastcast 
   
   2  ContentProvider,通过数据库存储 

   3  Sharapreference,前提是设置开放模式 

   4  文件 

   5   SystemProperty 存储,这个是临时存储,机器重启的话就清除了 


具体选哪种,根据实际情况选择, 当然能不用跨进程尽量不用,毕竟进程启动的开销会大些 

猜你喜欢

转载自252190908.iteye.com/blog/1958920