关于Service中bindService注意的几个问题
最近有用到Activity需要不断的从Service中获取数据,第一个想法肯定就是通过bind回调机制了,有几点概念模糊特此记录下:
单独使用bindService(),unbindService()会经历:->onCreate()->onBind()->Service running->onUnbind()
-> onDestroy() 。
单独使用startService(),stopService()会经历:->onCreate()->onStartCommand()->Service running-> onDestroy() 。
先调用startService(),再调用bindService()方法:
- 如果结束只调用unbindService(),那么只会执行到onUnbind(),将不会执行onDestroy():->onCreate()->onStartCommand()->onBind()->Service
running-> onUnbind()。 - 如果在unbindService后,在调用stopService(),那么:->onCreate()->onStartCommand()->onBind()->Service running->
onUnbind()->onDestroy() 。
4、关于停止Service,如果service是非绑定的,最终当任务完成时,为了节省系统资源,一定要停止service,可以通过stopSelf()来停止,也可以在其他组件中通过stopService()来停止,绑定的service可以通过onUnBind()来停止service。
关于Activity与Service数据的互相传递,写了个demo:
public class MainActivity extends Activity implements View.OnClickListener {
private TextView mTextView;
private EditText mEditText;
private MyService.LocalBinder binder=null;
MyService myService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.edt_content);
Button mBtnStart = (Button) findViewById(R.id.btn_start);
Button mBtnClose = (Button) findViewById(R.id.btn_close);
Button mBtnSubmit = (Button) findViewById(R.id.btn_submit);
mTextView = (TextView) findViewById(R.id.tv_show);
mBtnStart.setOnClickListener(this);
mBtnClose.setOnClickListener(this);
mBtnSubmit.setOnClickListener(this);
}
public ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (MyService.LocalBinder) service;//得到LocalBinder实例
myService = binder.getService();//得到Service实例
//设置接口回调获取Service中的数据
myService.setOnDataCallback(new MyService.OnDataCallback() {
@Override
public void onDataChange( final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mTextView.setText(message);
}
});
}
});
}
@Override
public void onServiceDisconnected(ComponentName name) {
myService = null;
}
};
@Override
public void onClick(View v) {
Intent intent = new Intent(this,MyService.class);
switch (v.getId()){
case R.id.btn_start:
// startService(intent);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);//为Activity绑定服务
break;
case R.id.btn_close:
unbindService(mServiceConnection);//解除绑定
// stopService(intent);
break;
case R.id.btn_submit:
if(binder!=null){
//把数据传给Service,相比用Bundle效率更高
binder.setData(mEditText.getText().toString());
}
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);//解除绑定
}
}
MyService:
public class MyService extends Service {
private String message ;
private boolean isRunning = true;
private IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
public void setData(String message) {
//从Activity传入message值
MyService.this.message = message;
}
public MyService getService() {
//返回当前MyService对象
return MyService.this;
}
}
private OnDataCallback mOnDataCallback=null;
public void setOnDataCallback(OnDataCallback mOnDataCallback) {
this.mOnDataCallback = mOnDataCallback;
}
public interface OnDataCallback{
void onDataChange(String message);
}
@Override
public IBinder onBind(Intent intent) {
//返回这个LocalBinder对象,其实这个对象可以在Activity中onServiceConnected()方法中接收到,这个bind就是Activity和Service通信的桥梁
//因为在Activity通过这个bind对象可以得到Service的实例引用。一旦Service对象找到,就能得到它的公共方法和属性。
return binder;
}
@Override
public void onCreate() {
super.onCreate();
new Thread() {
@Override
public void run() {
int i=1;
while (isRunning) {
if(mOnDataCallback!=null){
mOnDataCallback.onDataChange(message + i);
}
i++;
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
isRunning = false;
}
}
Activity能进行绑定得益于Service的接口onBind()。Service和Activity的连接可以用ServiceConnection来实现,需要实现一个新的ServiceConnection,重写onServiceConnected和onServiceDisconnected方法。执行绑定,调用bindService方法,传入一个选择了要绑定的Service的Intent(显式或隐式)和一个你实现了的ServiceConnection实例。一旦连接建立,你就能通Service的接口onBind()得到mBinder实例进而得到Service的实例引用。一旦Service对象找到,就能得到它的公共方法和属性。但这种方式,只能在同一个进程和同一个Application里。跨进程跨应用通信IPC需要建立aidl文件(注:Android5.0以后跨应用只能通过显示Intent来启动Service,即包名、类名)。
关于Service中bindService注意的几个问题的更多相关文章
- 【转】Android中BindService方式使用的理解
原文网址:http://www.cnblogs.com/onlylittlegod/archive/2011/05/15/2046652.html 最近学习了一下Android里面的Service的应 ...
- Service 中的 onStart 和 onStartCommand
在自定义的service中,写了onStart和onStartCommand, public class HttpWebService extends Service { @Override publ ...
- android中activity向service中传值
和activity中互相传值类似 在activity中 Intent regIntent = new Intent(this, ChatService.class); regIntent.putEx ...
- Android系统编程入门系列之服务Service中的进程间通信
在上篇文章以线程间的通信方式Handler类结尾,服务Service还支持的进程间通信,又是具体怎么实现的呢?这就要用到加载服务一文中提到的AIDL语言规范了. AIDL是 Android Inter ...
- 如何托管ASP.NET Core应用到Windows Service中
(此文章同时发表在本人微信公众号"dotNET开发经验谈",欢迎右边二维码来关注.) 题记:正在构思一个中间件的设计,考虑是否既可以使用最新的技术,也可以兼顾传统的部署模式.所以有 ...
- Web Service 中返回DataSet结果大小改进
http://www.cnblogs.com/scottckt/archive/2012/11/10/2764496.html Web Service 中返回DataSet结果方法: 1)直接返回Da ...
- 跟我学Windows Azure 四 Cloud Service中的WebRole与WorkRole,及他们之间的通信
Cloud Service 中WebRole就相当与我们的WebSite,而WorkRole相当与我们在服务器上写了个Windows Service,站在高可用的角度上来讲,Cloud Service ...
- JAVA CDI 学习(5) - 如何向RESTFul Service中注入EJB实例
RESTFul Service中如果要注入EJB实例,常规的@Inject将不起作用,在Jboss中,应用甚至都启动不起来(因为@Inject注入失败),解决方法很简单:将@Inject换成@EJB ...
- (原创)在service中定时执行网络操作的几点说明
执行网络操作是耗时操作,即便是在service中也要放到子线程中执行 这里我用到了async-http-client框架来执行异步请求操作 计时用的java原生Timer和TimerTask类 本来这 ...
随机推荐
- 23 服务IntentService Demo6
MainActivity.java package com.qf.day23_service_demo2; import android.app.Activity; import android.co ...
- FORM开发技术之动态控制某些item的属性
利用FORM内置函数控制ITEM包括按钮,普通ITEM等等的属性,更多内置函数学习课参考我的博客FORM内置系统函数 http://blog.csdn.net/cai_xingyun/article/ ...
- Android 使用DownloadManager进行版本更新的完整方案
在Android App都会有版本更新的功能,以前我们公司是用友盟SDK更新功能,自己服务器没有这样的功能.版本检测.Apk下载都是使用友盟.最近看到友盟的版本更新SDK文档:十月份更新功能将会停止服 ...
- Erlang的常驻模块与功能模块
Erlang的常驻模块与功能模块Residence moduleThe module where a process has its tail-recursive loop function(s).I ...
- JAVA面向对象-----多态
多态的概述 1:什么是多态 一个对象的多种状态 (老师)(员工)(儿子) 教师 a =老钟; 员工 b= 老钟; 2:多态体现 1:Father类 1:非静态成员变量x 2:静态成员变量y 3:非静态 ...
- RDD:基于内存的集群计算容错抽象
转载自:http://shiyanjun.cn/archives/744.html 摘要 本文提出了分布式内存抽象的概念--弹性分布式数据集(RDD,Resilient Distributed Dat ...
- 2.QT中操作word文档
Qt/Windows桌面版提供了ActiveQt框架,用以为Qt和ActiveX提供完美结合.ActiveQt由两个模块组成: A QAxContainer模块允许我们使用COM对象并且可以 ...
- 【Netty源码学习】EventLoopGroup
在上一篇博客[Netty源码解析]入门示例中我们介绍了一个Netty入门的示例代码,接下来的博客我们会分析一下整个demo工程运行过程的运行机制. 无论在Netty应用的客户端还是服务端都首先会初始化 ...
- 修改GDAL库支持IRSP6数据
使用GDAL库发现不能打开IRSP6的数据,不过看GDAL提供的文件格式里面却是支持IRSP6的数据的,具体可以参考网页http://www.gdal.org/frmt_fast.html.下面图1是 ...
- android PakageManagerService启动流程分析
PakageManagerService的启动流程图 1.PakageManagerService概述 PakageManagerService是android系统中一个核心的服务,它负责系统中Pac ...