博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Activity 和Service绑定
阅读量:4557 次
发布时间:2019-06-08

本文共 1495 字,大约阅读时间需要 4 分钟。

当一个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;

}

}

 

ServiceActivity的连接可以用ServiceConnection来实现。你需要实现一个新的ServiceConnection,重写onServiceConnectedonServiceDisconnected方法,一旦连接建立,你就能得到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方法,传入一个选择了要绑定的ServiceIntent(显式或隐式)和一个你实现了的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交互。

转载于:https://www.cnblogs.com/domybest/archive/2011/06/30/2094931.html

你可能感兴趣的文章
滚动条隐藏兼容写法
查看>>
SQL2005查询所有表的大小
查看>>
Shell 正则表达式
查看>>
Docker run命令参数整理
查看>>
qt-opencv配置mingw编译器
查看>>
CSS之Medial Queries的另一用法:实现IE hack的方法
查看>>
linux-CentOS6.4下安装oracle11g详解
查看>>
实力为王 八年DBA经验谈
查看>>
2-sat 问题 【例题 Flags(2-sat+线段树优化建图)】
查看>>
ext3.2 右击动态添加node的treepanel
查看>>
Database links
查看>>
1035 插入与归并(25 分)
查看>>
STL中排序函数的用法(Qsort,Sort,Stable_sort,Partial_sort,List::sort)
查看>>
如何解决php 生成验证码图片不显示问题
查看>>
PHP,javascript实现大文件上传
查看>>
c#图像处理算法学习
查看>>
webApi之FromUri和FromBody区别
查看>>
【SoapUI】http接口测试
查看>>
各种工具网站
查看>>
数据库事务
查看>>