分享

绑定service

 天天new 2014-12-04
当一个Activity绑定到一个Service上时,它负责维护Service实例的引用,允许你对正在运行的Service进行一些方法调用。
  • 1实现ServiceConnection.

    你的实现必须重写两个回调方法:

    • onServiceConnected()

      系统调用这个来传送在serviceonBind()中返回的IBinder

    • OnServiceDisconnected()

      Android系统在同service的连接意外丢失时调用这个.比如当service崩溃了或被强杀了.当客户端解除绑定时,这个方法不会被调用.


  • LocalService mService;  
  • private ServiceConnection mConnection = new ServiceConnection() {  
  •     // 当与service的连接建立后被调用  
  •     public void onServiceConnected(ComponentName className, IBinder service) {  
  •         // Because we have bound to an explicit  
  •         // service that is running in our own process, we can  
  •         // cast its IBinder to a concrete class and directly access it.  
  •         LocalBinder binder = (LocalBinder) service;  
  •         mService = binder.getService();  
  •         mBound = true;  
  •     }  
  •   
  •     // 当与service的连接意外断开时被调用  
  •     public void onServiceDisconnected(ComponentName className) {  
  •         Log.e(TAG, "onServiceDisconnected");  
  •         mBound = false;  
  •     }  
  • };  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多