`
meohao
  • 浏览: 94347 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

写在20120524:aidl

 
阅读更多
Android IDL =aidl 是一种idl(接口定义)语言,轻量级
它可以生成一段代码,可以使在一个Android设备上运行的两个进程使用内部通信进程进行交互。
1.建立一个aidl文件
package com.google.android.sample;
interface MDSInterface{
   void playFile(int position);
};
2.aidl会自动生成一个接口文件,文件名和aidl文件名一致,生成的接口包括一个内部抽象类,名称为Stub.
MSDTnterface.Stub mBindler = new MSDTnterface.Stub(){
   void playFile(int position){
     //To_do sth
   }
}
实现接口的几个原则:
1) 抛出的异常不要返回给调用者;
2) IPC调用是同步的,如果你知道一个IPC服务需要超过几毫秒的时间才能完成的话,你应该避免在Activity/View线程中调用
3) 只有方法才获得支持,换句话说不支持变量
4) 不能在aidl接口声明静态属性。
3.发布服务,继承Service,并实现getBinder()/onBind()返回一个实现的类的定制
public  class MDService extends Service{
   public IBinder onBind(Intent intent){
      return mBinder;
   }
   private final MDSInterface.Stub mBinder = new MSDTnterface.Stub(){
   }
}
4.被调用者调用
public class MusicDroid extends Activity{
    public MDSInterface mpInterface;
    publiv void onCreate(Bundle icicle){
    bindService(new Intent(MusicDroid.this, MDService.class), mConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection =new ServiceConnection(){
       public void onServiceConnected(ComponentName classname, IBinder service){
         mpInterface=MDSInterface.Stub.asInterface((IBinder).Service);
       }
       public void onServiceDisconnected(ComponentName classname){
         mpInterface = null;
       }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics