在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务,所以在我们实际开发中,就会常常遇到Activity与Service之间的通信,我们一般在Activity中启动后台Service,通过Intent来启动,Intent中我们可以传递数据给Service,而当我们Service执行某些操作之后想要更新UI线程,我们应该怎么做呢?接下来我就介绍两种方式来实现Service与Activity之间的通信问题
当Activity通过调用bindService(Intent service, ServiceConnection conn,int flags),我们可以得到一个Service的一个对象实例,然后我们就可以访问Service中的方法,我们还是通过一个例子来理解一下吧,一个模拟下载的小例子,带大家理解一下通过Binder通信的方式
首先我们新建一个工程Communication,然后新建一个Service类
-
<spanstyle="font-family:System;">packagecom.example.communication;
-
-
importandroid.app.Service;
-
importandroid.content.Intent;
-
importandroid.os.Binder;
-
importandroid.os.IBinder;
-
-
publicclassMsgServiceextendsService{
-
-
-
-
publicstaticfinalintMAX_PROGRESS=100;
-
-
-
-
privateintprogress=0;
-
-
-
-
-
-
publicintgetProgress(){
-
returnprogress;
-
}
-
-
-
-
-
publicvoidstartDownLoad(){
-
newThread(newRunnable(){
-
-
@Override
-
publicvoidrun(){
-
while(progress<MAX_PROGRESS){
-
progress+=5;
-
try{
-
Thread.sleep(1000);
-
}catch(InterruptedExceptione){
-
e.printStackTrace();
-
}
-
-
}
-
}
-
}).start();
-
}
-
-
-
-
-
-
@Override
-
publicIBinderonBind(Intentintent){
-
returnnewMsgBinder();
-
}
-
-
publicclassMsgBinderextendsBinder{
-
-
-
-
-
publicMsgServicegetService(){
-
returnMsgService.this;
-
}
-
}
-
-
}</span>
上面的代码比较简单,注释也比较详细,最基本的Service的应用了,相信你看得懂的,我们调用startDownLoad()方法来模拟下载任务,然后每秒更新一次进度,但这是在后台进行中,我们是看不到的,所以有时候我们需要他能在前台显示下载的进度问题,所以我们接下来就用到Activity了
-
Intentintent=newIntent("com.example.communication.MSG_ACTION");
-
bindService(intent,conn,Context.BIND_AUTO_CREATE);
通过上面的代码我们就在Activity绑定了一个Service,上面需要一个ServiceConnection对象,它是一个接口,我们这里使用了匿名内部类
-
<spanstyle="font-family:System;">ServiceConnectionconn=newServiceConnection(){
-
-
@Override
-
publicvoidonServiceDisconnected(ComponentNamename){
-
-
}
-
-
@Override
-
publicvoidonServiceConnected(ComponentNamename,IBinderservice){
-
-
msgService=((MsgService.MsgBinder)service).getService();
-
-
}
-
};</span>
在onServiceConnected(ComponentName name, IBinder service) 回调方法中,返回了一个MsgService中的Binder对象,我们可以通过getService()方法来得到一个MsgService对象,然后可以调用MsgService中的一些方法,Activity的代码如下
-
<spanstyle="font-family:System;">packagecom.example.communication;
-
-
importandroid.app.Activity;
-
importandroid.content.ComponentName;
-
importandroid.content.Context;
-
importandroid.content.Intent;
-
importandroid.content.ServiceConnection;
-
importandroid.os.Bundle;
-
importandroid.os.IBinder;
-
importandroid.view.View;
-
importandroid.view.View.OnClickListener;
-
importandroid.widget.Button;
-
importandroid.widget.ProgressBar;
-
-
publicclassMainActivityextendsActivity{
-
privateMsgServicemsgService;
-
privateintprogress=0;
-
privateProgressBarmProgressBar;
-
-
-
@Override
-
protectedvoidonCreate(BundlesavedInstanceState){
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main);
-
-
-
-
Intentintent=newIntent("com.example.communication.MSG_ACTION");
-
bindService(intent,conn,Context.BIND_AUTO_CREATE);
-
-
-
mProgressBar=(ProgressBar)findViewById(R.id.progressBar1);
-
ButtonmButton=(Button)findViewById(R.id.button1);
-
mButton.setOnClickListener(newOnClickListener(){
-
-
@Override
-
publicvoidonClick(Viewv){
-
-
msgService.startDownLoad();
-
-
listenProgress();
-
}
-
});
-
-
}
-
-
-
-
-
-
publicvoidlistenProgress(){
-
newThread(newRunnable(){
-
-
@Override
-
publicvoidrun(){
-
while(progress<MsgService.MAX_PROGRESS){
-
progress=msgService.getProgress();
-
mProgressBar.setProgress(progress);
-
try{
-
Thread.sleep(1000);
-
}catch(InterruptedExceptione){
-
e.printStackTrace();
-
}
-
}
-
-
}
-
}).start();
-
}
-
-
ServiceConnectionconn=newServiceConnection(){
-
@Override
-
publicvoidonServiceDisconnected(ComponentNamename){
-
-
}
-
-
@Override
-
publicvoidonServiceConnected(ComponentNamename,IBinderservice){
-
-
msgService=((MsgService.MsgBinder)service).getService();
-
-
}
-
};
-
-
@Override
-
protectedvoidonDestroy(){
-
unbindService(conn);
-
super.onDestroy();
-
}
-
-
-
}</span><spanstyle="font-family:simsun;">
-
</span>
其实上面的代码我还是有点疑问,就是监听进度变化的那个方法我是直接在线程中更新UI的,不是说不能在其他线程更新UI操作吗,可能是ProgressBar比较特殊吧,我也没去研究它的源码,知道的朋友可以告诉我一声,谢谢!
上面的代码就完成了在Service更新UI的操作,可是你发现了没有,我们每次都要主动调用getProgress()来获取进度值,然后隔一秒在调用一次getProgress()方法,你会不会觉得很被动呢?可不可以有一种方法当Service中进度发生变化主动通知Activity,答案是肯定的,我们可以利用回调接口实现Service的主动通知,不理解回调方法的可以看看http://blog.csdn.net/xiaanming/article/details/8703708
新建一个回调接口
-
publicinterfaceOnProgressListener{
-
voidonProgress(intprogress);
-
}
MsgService的代码有一些小小的改变,为了方便大家看懂,我还是将所有代码贴出来
-
<spanstyle="font-family:System;">packagecom.example.communication;
-
-
importandroid.app.Service;
-
importandroid.content.Intent;
-
importandroid.os.Binder;
-
importandroid.os.IBinder;
-
-
publicclassMsgServiceextendsService{
-
-
-
-
publicstaticfinalintMAX_PROGRESS=100;
-
-
-
-
privateintprogress=0;
-
-
-
-
-
privateOnProgressListeneronProgressListener;
-
-
-
-
-
-
-
publicvoidsetOnProgressListener(OnProgressListeneronProgressListener){
-
this.onProgressListener=onProgressListener;
-
}
-
-
-
-
-
-
publicintgetProgress(){
-
returnprogress;
-
}
-
-
-
-
-
publicvoidstartDownLoad(){
-
newThread(newRunnable(){
-
-
@Override
-
publicvoidrun(){
-
while(progress<MAX_PROGRESS){
-
progress+=5;
-
-
-
if(onProgressListener!=null){
-
onProgressListener.onProgress(progress);
-
}
-
-
try{
-
Thread.sleep(1000);
-
}catch(InterruptedExceptione){
-
e.printStackTrace();
-
}
-
-
}
-
}
-
}).start();
-
}
-
-
-
-
-
-
@Override
-
publicIBinderonBind(Intentintent){
-
returnnewMsgBinder();
-
}
-
-
publicclassMsgBinderextendsBinder{
-
-
-
-
-
publicMsgServicegetService(){
-
returnMsgService.this;
-
}
-
}
-
-
}</span>
Activity中的代码如下
-
<spanstyle="font-family:System;">packagecom.example.communication;
-
-
importandroid.app.Activity;
-
importandroid.content.ComponentName;
-
importandroid.content.Context;
-
importandroid.content.Intent;
-
importandroid.content.ServiceConnection;
-
importandroid.os.Bundle;
-
importandroid.os.IBinder;
-
importandroid.view.View;
-
importandroid.view.View.OnClickListener;
-
importandroid.widget.Button;
-
importandroid.widget.ProgressBar;
-
-
publicclassMainActivityextendsActivity{
-
privateMsgServicemsgService;
-
privateProgressBarmProgressBar;
-
-
-
@Override
-
protectedvoidonCreate(BundlesavedInstanceState){
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main);
-
-
-
-
Intentintent=newIntent("com.example.communication.MSG_ACTION");
-
bindService(intent,conn,Context.BIND_AUTO_CREATE);
-
-
-
mProgressBar=(ProgressBar)findViewById(R.id.progressBar1);
-
ButtonmButton=(Button)findViewById(R.id.button1);
-
mButton.setOnClickListener(newOnClickListener(){
-
-
@Override
-
publicvoidonClick(Viewv){
-
-
msgService.startDownLoad();
-
}
-
});
-
-
}
-
-
-
ServiceConnectionconn=newServiceConnection(){
-
@Override
-
publicvoidonServiceDisconnected(ComponentNamename){
-
-
}
-
-
@Override
-
publicvoidonServiceConnected(ComponentNamename,IBinderservice){
-
-
msgService=((MsgService.MsgBinder)service).getService();
-
-
-
msgService.setOnProgressListener(newOnProgressListener(){
-
-
@Override
-
publicvoidonProgress(intprogress){
-
mProgressBar.setProgress(progress);
-
-
}
-
});
-
-
}
-
};
-
-
@Override
-
protectedvoidonDestroy(){
-
unbindService(conn);
-
super.onDestroy();
-
}
-
-
-
}
-
</span>
用回调接口是不是更加的方便呢,当进度发生变化的时候Service主动通知Activity,Activity就可以更新UI操作了
当我们的进度发生变化的时候我们发送一条广播,然后在Activity的注册广播接收器,接收到广播之后更新ProgressBar,代码如下
-
packagecom.example.communication;
-
<spanstyle="font-family:System;">
-
importandroid.app.Activity;
-
importandroid.content.BroadcastReceiver;
-
importandroid.content.Context;
-
importandroid.content.Intent;
-
importandroid.content.IntentFilter;
-
importandroid.os.Bundle;
-
importandroid.view.View;
-
importandroid.view.View.OnClickListener;
-
importandroid.widget.Button;
-
importandroid.widget.ProgressBar;
-
-
publicclassMainActivityextendsActivity{
-
privateProgressBarmProgressBar;
-
privateIntentmIntent;
-
privateMsgReceivermsgReceiver;
-
-
-
@Override
-
protectedvoidonCreate(BundlesavedInstanceState){
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main);
-
-
-
msgReceiver=newMsgReceiver();
-
IntentFilterintentFilter=newIntentFilter();
-
intentFilter.addAction("com.example.communication.RECEIVER");
-
registerReceiver(msgReceiver,intentFilter);
-
-
-
mProgressBar=(ProgressBar)findViewById(R.id.progressBar1);
-
ButtonmButton=(Button)findViewById(R.id.button1);
-
mButton.setOnClickListener(newOnClickListener(){
-
-
@Override
-
publicvoidonClick(Viewv){
-
-
mIntent=newIntent("com.example.communication.MSG_ACTION");
-
startService(mIntent);
-
}
-
});
-
-
}
-
-
-
@Override
-
protectedvoidonDestroy(){
-
-
stopService(mIntent);
-
-
unregisterReceiver(msgReceiver);
-
super.onDestroy();
-
}
-
-
-
-
-
-
-
-
publicclassMsgReceiverextendsBroadcastReceiver{
-
-
@Override
-
publicvoidonReceive(Contextcontext,Intentintent){
-
-
intprogress=intent.getIntExtra("progress",0);
-
mProgressBar.setProgress(progress);
-
}
-
-
}
-
-
}
-
</span>
-
<spanstyle="font-family:System;">packagecom.example.communication;
-
-
importandroid.app.Service;
-
importandroid.content.Intent;
-
importandroid.os.IBinder;
-
-
publicclassMsgServiceextendsService{
-
-
-
-
publicstaticfinalintMAX_PROGRESS=100;
-
-
-
-
privateintprogress=0;
-
-
privateIntentintent=newIntent("com.example.communication.RECEIVER");
-
-
-
-
-
-
publicvoidstartDownLoad(){
-
newThread(newRunnable(){
-
-
@Override
-
publicvoidrun(){
-
while(progress<MAX_PROGRESS){
-
progress+=5;
-
-
-
intent.putExtra("progress",progress);
-
sendBroadcast(intent);
-
-
try{
-
Thread.sleep(1000);
-
}catch(InterruptedExceptione){
-
e.printStackTrace();
-
}
-
-
}
-
}
-
}).start();
-
}
-
-
-
-
@Override
-
publicintonStartCommand(Intentintent,intflags,intstartId){
-
startDownLoad();
-
returnsuper.onStartCommand(intent,flags,startId);
-
}
-
-
-
-
@Override
-
publicIBinderonBind(Intentintent){
-
returnnull;
-
}
-
-
-
总结:
- Activity调用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service对象的一个引用,这样Activity可以直接调用到Service中的方法,如果要主动通知Activity,我们可以利用回调方法
- Service向Activity发送消息,可以使用广播,当然Activity要注册相应的接收器。比如Service要向多个Activity发送同样的消息的话,用这种方法就更好
分享到:
相关推荐
本篇文章主要介绍了Android中Service与Activity之间通信的几种方式,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务,具有一定的参考价值,有兴趣的可以了解一下。
在Android中,Activity主要负责前台页面的展示,Service主要...接下来我就介绍两种方式来实现Service与Activity之间的通信问题 通过Binder对象 当Activity通过调用bindService(Intent service, ServiceConnection co
主要介绍了Android Activity与Service通信(不同进程之间)的相关资料,这里提供了三种方法,需要的朋友可以参考下
这4种方式正好对应于android系统中4种应用程序组件:Activity、Content Provider、Broadcast和Service。其中Activity可以跨进程调用其他应用程序的Activity;Content Provider可以跨进程访问其他应用程序中的数据...
描述 :整理了下android中的aidl, 项目中主要是用作于Activity和Service之间进行跨进程的通信和调用,定义了几种基本类型的接口,其中涵盖了自定义参数类型的传递。 注意: 解压后有两个android程序,一个client端 ...
注:只是说明启动activity的过程(ActivityThread如何与ActivityManagerService简称AmS进行进程间通信调用全过程),不解析android从zygote(受精卵)到整个系统服务的启动 具体来讲,启动activity的方式有以下几种...
----------------------------------- Android 编程基础 1 封面----------------------------------- Android 编程基础 2 开放手机联盟 --Open --Open --Open --Open Handset Handset Handset Handset Alliance ...
两种启动方式的区别2.Service启动流程3.Service与Activity怎么实现通信4.IntentService是什么,IntentService原理,应用场景及其与Service的区别5.Service 的 onStartCommand 方法有几种返回值?各代表什么意思?6....
Android平板开发需要注意的几点 Android3D游戏开发付费视频教程共享(更新第四集) 史上最全示例Android教学视频,非常值得观看 Android游戏开发系列源码+CHM+书籍截图+目录】 Android developer guide中文翻译...
第9章分析了Vold和Rild,其中Vold负责Android平台中外部存储设备的管理,而Rild负责与射频通信有关的工作。本章的拓展思考部分介绍了嵌入式系统中与存储有关的知识,还探讨了 Rild和Phone设计优化方面的问题。 ...
注册广播有几种方式,这些方式有何优缺点?请谈谈Android引入广播机制的用意。 答:两种,一种是xml注册,一种是代码注册 xml注册的优点:方便、易读 缺点:当手机处于关机状态时,仍然可以监听到广播,不...
◆与电话和网络硬件相关的所有内容,如电话api、sms和网络管理等 ◆高级开发主题,包括安全、ipc以及一些高级图形和用户界面技术 读者对象 本书面向希望在android手机平台上创建应用程序的所有人员。不管是...
1 Activity 与 Fragment 之间常见的几种通信方式? 2 LaunchMode 的应用场景? 3 BroadcastReceiver 与LocalBroadcastReceiver 有什么区别? 4 对于 Context,你了解多少? 5 IntentFilter是什么?有哪些使用场景? 6...
|--缓存优化之几种方案lastModified |--缓存优化之本地缓存优化(超过规定值或SD卡容量不够时) |--网络post提交查询请求 |--网络之HttpClient的get和post用法 |--网络之判断网络状态是否可用 |--网络之设置apn |--...