打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Activity 和Service绑定

  当一个Activity绑定到一个Service上时,它负责维护Service实例的引用,允许你对正在运行的Service进行一些方法调用。
 
  Activity能进行绑定得益于Service的接口。为了支持Service的绑定,实现onBind方法如下所示:
 
  private final IBinder binder = new MyBinder();
 
    @Override
   public IBinder onBind(Intent intent) {
       return binder;
   }
 
   public class MyBinder extends Binder {
     MyService getService()
     {
      return MyService.this;
     }
   }

  Service和Activity的连接可以用ServiceConnection来实现。你需要实现一个新的ServiceConnection,重写onServiceConnected和onServiceDisconnected方法,一旦连接建立,你就能得到Service实例的引用。
 
  // Reference to the service
  private MyService serviceBinder;
 
  // Handles the connection between the service and activity
  private ServiceConnection mConnection = new ServiceConnection()
  {
  public void onServiceConnected(ComponentName className, IBinder service) {
  // Called when the connection is made.
  serviceBinder = ((MyService.MyBinder)service).getService();
  }
 
  public void onServiceDisconnected(ComponentName className) {
  // Received when the service unexpectedly disconnects.
  serviceBinder = null;
  }
  };
 
  执行绑定,调用bindService方法,传入一个选择了要绑定的Service的Intent(显式或隐式)和一个你实现了的ServiceConnection实例,如下的框架代码所示:
 
  @Override
  public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  // Bind to the service
  Intent bindIntent = new Intent(MyActivity.this, MyService.class);
  bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
  }
 
  一旦Service对象找到,通过onServiceConnected处理函数中获得serviceBinder对象就能得到它的公共方法和属性。
 
  Android应用程序一般不共享内存,但在有些时候,你的应用程序可能想要与其它的应用程序中运行的Service交互。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
android自定义一个本地服务的方法
android笔记
[z]Activity与Service通信
Android 绑定Service 实现android控制service的生命周期
Android中的Service的通信
17、从头学Android之Service初步二
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服