• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
袜子不回头
一个人走着走着摔倒了,爬起来,又摔倒了,又爬起来,又摔倒了,死循环了……
博客园    首页    新随笔    联系   管理    订阅  订阅

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交互。

posted @ 2011-06-30 18:42  袜子不回头  阅读(473)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3