Android Service与Activity之间通信的几种方式

本文详细介绍了在Android应用开发中如何通过Binder对象、回调接口和广播三种方式实现Activity与Service之间的通信,包括模拟下载任务的进度更新、主动通知Activity进度变化以及通过广播接收器接收消息等具体实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务,所以在我们实际开发中,就会常常遇到Activity与Service之间的通信,我们一般在Activity中启动后台Service,通过Intent来启动,Intent中我们可以传递数据给Service,而当我们Service执行某些操作之后想要更新UI线程,我们应该怎么做呢?接下来我就介绍两种方式来实现Service与Activity之间的通信问题

  • 通过Binder对象

当Activity通过调用bindService(Intent service, ServiceConnection conn,int flags),我们可以得到一个Service的一个对象实例,然后我们就可以访问Service中的方法,我们还是通过一个例子来理解一下吧,一个模拟下载的小例子,带大家理解一下通过Binder通信的方式

首先我们新建一个工程Communication,然后新建一个Service类

[java] view plain copy
  1. <spanstyle="font-family:System;">packagecom.example.communication;
  2. importandroid.app.Service;
  3. importandroid.content.Intent;
  4. importandroid.os.Binder;
  5. importandroid.os.IBinder;
  6. publicclassMsgServiceextendsService{
  7. /**
  8. *进度条的最大值
  9. */
  10. publicstaticfinalintMAX_PROGRESS=100;
  11. /**
  12. *进度条的进度值
  13. */
  14. privateintprogress=0;
  15. /**
  16. *增加get()方法,供Activity调用
  17. *@return下载进度
  18. */
  19. publicintgetProgress(){
  20. returnprogress;
  21. }
  22. /**
  23. *模拟下载任务,每秒钟更新一次
  24. */
  25. publicvoidstartDownLoad(){
  26. newThread(newRunnable(){
  27. @Override
  28. publicvoidrun(){
  29. while(progress<MAX_PROGRESS){
  30. progress+=5;
  31. try{
  32. Thread.sleep(1000);
  33. }catch(InterruptedExceptione){
  34. e.printStackTrace();
  35. }
  36. }
  37. }
  38. }).start();
  39. }
  40. /**
  41. *返回一个Binder对象
  42. */
  43. @Override
  44. publicIBinderonBind(Intentintent){
  45. returnnewMsgBinder();
  46. }
  47. publicclassMsgBinderextendsBinder{
  48. /**
  49. *获取当前Service的实例
  50. *@return
  51. */
  52. publicMsgServicegetService(){
  53. returnMsgService.this;
  54. }
  55. }
  56. }</span>
上面的代码比较简单,注释也比较详细,最基本的Service的应用了,相信你看得懂的,我们调用startDownLoad()方法来模拟下载任务,然后每秒更新一次进度,但这是在后台进行中,我们是看不到的,所以有时候我们需要他能在前台显示下载的进度问题,所以我们接下来就用到Activity了

[java] view plain copy
  1. Intentintent=newIntent("com.example.communication.MSG_ACTION");
  2. bindService(intent,conn,Context.BIND_AUTO_CREATE);

通过上面的代码我们就在Activity绑定了一个Service,上面需要一个ServiceConnection对象,它是一个接口,我们这里使用了匿名内部类

[java] view plain copy
  1. <spanstyle="font-family:System;">ServiceConnectionconn=newServiceConnection(){
  2. @Override
  3. publicvoidonServiceDisconnected(ComponentNamename){
  4. }
  5. @Override
  6. publicvoidonServiceConnected(ComponentNamename,IBinderservice){
  7. //返回一个MsgService对象
  8. msgService=((MsgService.MsgBinder)service).getService();
  9. }
  10. };</span>

在onServiceConnected(ComponentName name, IBinder service) 回调方法中,返回了一个MsgService中的Binder对象,我们可以通过getService()方法来得到一个MsgService对象,然后可以调用MsgService中的一些方法,Activity的代码如下

[java] view plain copy
  1. <spanstyle="font-family:System;">packagecom.example.communication;
  2. importandroid.app.Activity;
  3. importandroid.content.ComponentName;
  4. importandroid.content.Context;
  5. importandroid.content.Intent;
  6. importandroid.content.ServiceConnection;
  7. importandroid.os.Bundle;
  8. importandroid.os.IBinder;
  9. importandroid.view.View;
  10. importandroid.view.View.OnClickListener;
  11. importandroid.widget.Button;
  12. importandroid.widget.ProgressBar;
  13. publicclassMainActivityextendsActivity{
  14. privateMsgServicemsgService;
  15. privateintprogress=0;
  16. privateProgressBarmProgressBar;
  17. @Override
  18. protectedvoidonCreate(BundlesavedInstanceState){
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. //绑定Service
  22. Intentintent=newIntent("com.example.communication.MSG_ACTION");
  23. bindService(intent,conn,Context.BIND_AUTO_CREATE);
  24. mProgressBar=(ProgressBar)findViewById(R.id.progressBar1);
  25. ButtonmButton=(Button)findViewById(R.id.button1);
  26. mButton.setOnClickListener(newOnClickListener(){
  27. @Override
  28. publicvoidonClick(Viewv){
  29. //开始下载
  30. msgService.startDownLoad();
  31. //监听进度
  32. listenProgress();
  33. }
  34. });
  35. }
  36. /**
  37. *监听进度,每秒钟获取调用MsgService的getProgress()方法来获取进度,更新UI
  38. */
  39. publicvoidlistenProgress(){
  40. newThread(newRunnable(){
  41. @Override
  42. publicvoidrun(){
  43. while(progress<MsgService.MAX_PROGRESS){
  44. progress=msgService.getProgress();
  45. mProgressBar.setProgress(progress);
  46. try{
  47. Thread.sleep(1000);
  48. }catch(InterruptedExceptione){
  49. e.printStackTrace();
  50. }
  51. }
  52. }
  53. }).start();
  54. }
  55. ServiceConnectionconn=newServiceConnection(){
  56. @Override
  57. publicvoidonServiceDisconnected(ComponentNamename){
  58. }
  59. @Override
  60. publicvoidonServiceConnected(ComponentNamename,IBinderservice){
  61. //返回一个MsgService对象
  62. msgService=((MsgService.MsgBinder)service).getService();
  63. }
  64. };
  65. @Override
  66. protectedvoidonDestroy(){
  67. unbindService(conn);
  68. super.onDestroy();
  69. }
  70. }</span><spanstyle="font-family:simsun;">
  71. </span>
其实上面的代码我还是有点疑问,就是监听进度变化的那个方法我是直接在线程中更新UI的,不是说不能在其他线程更新UI操作吗,可能是ProgressBar比较特殊吧,我也没去研究它的源码,知道的朋友可以告诉我一声,谢谢!

上面的代码就完成了在Service更新UI的操作,可是你发现了没有,我们每次都要主动调用getProgress()来获取进度值,然后隔一秒在调用一次getProgress()方法,你会不会觉得很被动呢?可不可以有一种方法当Service中进度发生变化主动通知Activity,答案是肯定的,我们可以利用回调接口实现Service的主动通知,不理解回调方法的可以看看http://blog.youkuaiyun.com/xiaanming/article/details/8703708

新建一个回调接口

[java] view plain copy
  1. publicinterfaceOnProgressListener{
  2. voidonProgress(intprogress);
  3. }
MsgService的代码有一些小小的改变,为了方便大家看懂,我还是将所有代码贴出来

[java] view plain copy
  1. <spanstyle="font-family:System;">packagecom.example.communication;
  2. importandroid.app.Service;
  3. importandroid.content.Intent;
  4. importandroid.os.Binder;
  5. importandroid.os.IBinder;
  6. publicclassMsgServiceextendsService{
  7. /**
  8. *进度条的最大值
  9. */
  10. publicstaticfinalintMAX_PROGRESS=100;
  11. /**
  12. *进度条的进度值
  13. */
  14. privateintprogress=0;
  15. /**
  16. *更新进度的回调接口
  17. */
  18. privateOnProgressListeneronProgressListener;
  19. /**
  20. *注册回调接口的方法,供外部调用
  21. *@paramonProgressListener
  22. */
  23. publicvoidsetOnProgressListener(OnProgressListeneronProgressListener){
  24. this.onProgressListener=onProgressListener;
  25. }
  26. /**
  27. *增加get()方法,供Activity调用
  28. *@return下载进度
  29. */
  30. publicintgetProgress(){
  31. returnprogress;
  32. }
  33. /**
  34. *模拟下载任务,每秒钟更新一次
  35. */
  36. publicvoidstartDownLoad(){
  37. newThread(newRunnable(){
  38. @Override
  39. publicvoidrun(){
  40. while(progress<MAX_PROGRESS){
  41. progress+=5;
  42. //进度发生变化通知调用方
  43. if(onProgressListener!=null){
  44. onProgressListener.onProgress(progress);
  45. }
  46. try{
  47. Thread.sleep(1000);
  48. }catch(InterruptedExceptione){
  49. e.printStackTrace();
  50. }
  51. }
  52. }
  53. }).start();
  54. }
  55. /**
  56. *返回一个Binder对象
  57. */
  58. @Override
  59. publicIBinderonBind(Intentintent){
  60. returnnewMsgBinder();
  61. }
  62. publicclassMsgBinderextendsBinder{
  63. /**
  64. *获取当前Service的实例
  65. *@return
  66. */
  67. publicMsgServicegetService(){
  68. returnMsgService.this;
  69. }
  70. }
  71. }</span>
Activity中的代码如下

[java] view plain copy
  1. <spanstyle="font-family:System;">packagecom.example.communication;
  2. importandroid.app.Activity;
  3. importandroid.content.ComponentName;
  4. importandroid.content.Context;
  5. importandroid.content.Intent;
  6. importandroid.content.ServiceConnection;
  7. importandroid.os.Bundle;
  8. importandroid.os.IBinder;
  9. importandroid.view.View;
  10. importandroid.view.View.OnClickListener;
  11. importandroid.widget.Button;
  12. importandroid.widget.ProgressBar;
  13. publicclassMainActivityextendsActivity{
  14. privateMsgServicemsgService;
  15. privateProgressBarmProgressBar;
  16. @Override
  17. protectedvoidonCreate(BundlesavedInstanceState){
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. //绑定Service
  21. Intentintent=newIntent("com.example.communication.MSG_ACTION");
  22. bindService(intent,conn,Context.BIND_AUTO_CREATE);
  23. mProgressBar=(ProgressBar)findViewById(R.id.progressBar1);
  24. ButtonmButton=(Button)findViewById(R.id.button1);
  25. mButton.setOnClickListener(newOnClickListener(){
  26. @Override
  27. publicvoidonClick(Viewv){
  28. //开始下载
  29. msgService.startDownLoad();
  30. }
  31. });
  32. }
  33. ServiceConnectionconn=newServiceConnection(){
  34. @Override
  35. publicvoidonServiceDisconnected(ComponentNamename){
  36. }
  37. @Override
  38. publicvoidonServiceConnected(ComponentNamename,IBinderservice){
  39. //返回一个MsgService对象
  40. msgService=((MsgService.MsgBinder)service).getService();
  41. //注册回调接口来接收下载进度的变化
  42. msgService.setOnProgressListener(newOnProgressListener(){
  43. @Override
  44. publicvoidonProgress(intprogress){
  45. mProgressBar.setProgress(progress);
  46. }
  47. });
  48. }
  49. };
  50. @Override
  51. protectedvoidonDestroy(){
  52. unbindService(conn);
  53. super.onDestroy();
  54. }
  55. }
  56. </span>
用回调接口是不是更加的方便呢,当进度发生变化的时候Service主动通知Activity,Activity就可以更新UI操作了

当我们的进度发生变化的时候我们发送一条广播,然后在Activity的注册广播接收器,接收到广播之后更新ProgressBar,代码如下

[java] view plain copy
  1. packagecom.example.communication;
  2. <spanstyle="font-family:System;">
  3. importandroid.app.Activity;
  4. importandroid.content.BroadcastReceiver;
  5. importandroid.content.Context;
  6. importandroid.content.Intent;
  7. importandroid.content.IntentFilter;
  8. importandroid.os.Bundle;
  9. importandroid.view.View;
  10. importandroid.view.View.OnClickListener;
  11. importandroid.widget.Button;
  12. importandroid.widget.ProgressBar;
  13. publicclassMainActivityextendsActivity{
  14. privateProgressBarmProgressBar;
  15. privateIntentmIntent;
  16. privateMsgReceivermsgReceiver;
  17. @Override
  18. protectedvoidonCreate(BundlesavedInstanceState){
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. //动态注册广播接收器
  22. msgReceiver=newMsgReceiver();
  23. IntentFilterintentFilter=newIntentFilter();
  24. intentFilter.addAction("com.example.communication.RECEIVER");
  25. registerReceiver(msgReceiver,intentFilter);
  26. mProgressBar=(ProgressBar)findViewById(R.id.progressBar1);
  27. ButtonmButton=(Button)findViewById(R.id.button1);
  28. mButton.setOnClickListener(newOnClickListener(){
  29. @Override
  30. publicvoidonClick(Viewv){
  31. //启动服务
  32. mIntent=newIntent("com.example.communication.MSG_ACTION");
  33. startService(mIntent);
  34. }
  35. });
  36. }
  37. @Override
  38. protectedvoidonDestroy(){
  39. //停止服务
  40. stopService(mIntent);
  41. //注销广播
  42. unregisterReceiver(msgReceiver);
  43. super.onDestroy();
  44. }
  45. /**
  46. *广播接收器
  47. *@authorlen
  48. *
  49. */
  50. publicclassMsgReceiverextendsBroadcastReceiver{
  51. @Override
  52. publicvoidonReceive(Contextcontext,Intentintent){
  53. //拿到进度,更新UI
  54. intprogress=intent.getIntExtra("progress",0);
  55. mProgressBar.setProgress(progress);
  56. }
  57. }
  58. }
  59. </span>

[java] view plain copy
  1. <spanstyle="font-family:System;">packagecom.example.communication;
  2. importandroid.app.Service;
  3. importandroid.content.Intent;
  4. importandroid.os.IBinder;
  5. publicclassMsgServiceextendsService{
  6. /**
  7. *进度条的最大值
  8. */
  9. publicstaticfinalintMAX_PROGRESS=100;
  10. /**
  11. *进度条的进度值
  12. */
  13. privateintprogress=0;
  14. privateIntentintent=newIntent("com.example.communication.RECEIVER");
  15. /**
  16. *模拟下载任务,每秒钟更新一次
  17. */
  18. publicvoidstartDownLoad(){
  19. newThread(newRunnable(){
  20. @Override
  21. publicvoidrun(){
  22. while(progress<MAX_PROGRESS){
  23. progress+=5;
  24. //发送Action为com.example.communication.RECEIVER的广播
  25. intent.putExtra("progress",progress);
  26. sendBroadcast(intent);
  27. try{
  28. Thread.sleep(1000);
  29. }catch(InterruptedExceptione){
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34. }).start();
  35. }
  36. @Override
  37. publicintonStartCommand(Intentintent,intflags,intstartId){
  38. startDownLoad();
  39. returnsuper.onStartCommand(intent,flags,startId);
  40. }
  41. @Override
  42. publicIBinderonBind(Intentintent){
  43. returnnull;
  44. }
  45. 总结:

    1. Activity调用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service对象的一个引用,这样Activity可以直接调用到Service中的方法,如果要主动通知Activity,我们可以利用回调方法
    2. Service向Activity发送消息,可以使用广播,当然Activity要注册相应的接收器。比如Service要向多个Activity发送同样的消息的话,用这种方法就更好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值