android activity和service的交互介绍

Android开发中,作为4大组件的service在开发中经常会使用到。很多时候,我们的activity和service之间需要进行相应的交互,activity需要调用service里面的方法实现某些功能,service需要调用activity的方法,实现界面更新等的交互。


实现2者之间相互交互的主要方式是:service中有个类部类继承Binder,然后提供一个公有方法,返回当前service的实例。 activity通过bindService来开启一个service,service通过onBind方法,返回一个IBinder实例(我们创建的那个类部类实例),activity中通过onServiceConnected方法,获取IBinder实例,然后再通过IBinder实例来获取service实例,这样,我们得到了service的实例,那么我们的activity就可以随心所欲的使用它里面的各种方法来操作它了。



上面activity可以操作service了,我们还需要service能操作activity。

我觉得可以有3中方式:

1.直接把activity传给service,service通过activity实例随便操作activity

2.使用接口回调方式,activity实现相应的接口,service通过接口进行回调,比较灵活

3.使用广播


使用广播是比较常见的方式,我们就不具体讲解了,下面我们介绍前面2中方法,具体看代码,用service更新seekbar。

我们的activity代码:

[html]  view plain  copy
  1. package com.hck.bindservice;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ComponentName;  
  5. import android.content.Intent;  
  6. import android.content.ServiceConnection;  
  7. import android.os.Bundle;  
  8. import android.os.IBinder;  
  9. import android.util.Log;  
  10. import android.view.View;  
  11. import android.widget.SeekBar;  
  12. import android.widget.Toast;  
  13.   
  14. import com.hck.bindservice.MyService.MyBuild;  
  15.   
  16. public class MainActivity extends Activity {  
  17.    private MyService myService;  //我们自己的service  
  18.    private SeekBar pBar;  //模拟service更新进度条  
  19.    private ConnectionService connectionService;  
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.main);  
  24.         pBar = (SeekBar) findViewById(R.id.seekbar);  
  25.         connectionService=new ConnectionService();     
  26.     }  
  27.   
  28.     public void startService(View view) { //绑定service  
  29.        bindService(new Intent(this,MyService.class), connectionService, 1);  
  30.     }  
  31.     /**  
  32.      *   
  33.      * @author Administrator  
  34.      *实现service接口,用于service绑定时候,回调  
  35.      */  
  36.     class ConnectionService  implements ServiceConnection  
  37.     {  
  38.         @Override  
  39.         public void onServiceConnected(ComponentName name, IBinder service) {  
  40.             myService=((MyBuild)service).getMyService(); //获取Myservice对象  
  41.               
  42.             /**  
  43.              * 直接把当前对象传给service,这样service就可以随心所欲的调用本activity的各种可用方法  
  44.              */  
  45.             myService.setMainActivity(MainActivity.this); //把当前对象传递给myservice  
  46.               
  47.               
  48.             /**  
  49.              * 使用一个接口来实现回调,这样比上面方法更加灵活,推荐  
  50.              */  
  51. //          myService.setOnProgressBarListener(new UpdateProgressListener() {  
  52. //                
  53. //              @Override  
  54. //              public void updateBar(int size) {  
  55. //                  updateBar(size);  
  56. //              }  
  57. //          });  
  58.               
  59.         }  
  60.   
  61.         @Override  
  62.         public void onServiceDisconnected(ComponentName name) {  
  63.               
  64.         }  
  65.     }  
  66.     /**  
  67.      *   
  68.      * @param size  
  69.      * 更新seekbar  
  70.      */  
  71.     public void updateBar(int size)  
  72.     {  
  73.         pBar.setProgress(size);  
  74.     }  
  75.       
  76.     /**  
  77.      *   
  78.      * @param view  
  79.      * 开始更新seekbar  
  80.      */  
  81.     public void startBar(View view) {  
  82.           if (myService==null) {  
  83.             Toast.makeText(this, "请先开始service", Toast.LENGTH_LONG).show();  
  84.          }  
  85.           else {  
  86.             myService.startUpdateProgress();  
  87.         }  
  88.         }  
  89. /**  
  90.  *   
  91.  * @param view  
  92.  * 停止更新seekbar  
  93.  */  
  94.         public void stopBar(View view) {  
  95.               
  96.              if (myService==null) {  
  97.                     Toast.makeText(this, "更新没有开始", Toast.LENGTH_LONG).show();  
  98.                  }  
  99.                   else {  
  100.                     myService.stopUpdateProgress();  
  101.                 }  
  102.         }  
  103. /**  
  104.  *   
  105.  * @param view  
  106.  * 停止service  
  107.  */  
  108.         public void stopService(View view) {  
  109.             myService=null;  
  110.                 unbindService(connectionService);  
  111.               
  112.               
  113.               
  114.               
  115.         }  
  116.         @Override  
  117.             protected void onDestroy() {  
  118.                 super.onDestroy();  
  119.                 try {  
  120.                     unbindService(connectionService);  
  121.                 } catch (Exception e) {  
  122.                 }  
  123.                   
  124.             }  
  125.   
  126.   
  127. }  


重要代码是onServiceConnected回调方法里面

myService=((MyBuild)service).getMyService(); //获取Myservice对象

获取service对象后,我们想怎么操作它都行了,比如上面的,把activity实例直接通过它的方法传递过去,便于

service调用activity的各种方法。或者,设置传递一个回调接口对象过去,用户回调



service代码:

[html]  view plain  copy
  1. package com.hck.bindservice;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.Handler;  
  7. import android.os.IBinder;  
  8. import android.util.Log;  
  9.   
  10. public class MyService extends Service{  
  11.    private int size=0;    
  12.    private UpdateProgress updateProgress;  
  13.    private final long TIME=2000;  
  14.    private boolean isUpdate=true;  
  15.    private MainActivity activity;  
  16.    private UpdateProgressListener listener;  
  17.     @Override  
  18.     public IBinder onBind(Intent intent) {  
  19.           
  20.         return new MyBuild();  
  21.     }  
  22.     @Override  
  23.     public void onCreate() {  
  24.         super.onCreate();  
  25.         updateProgress=new UpdateProgress();  
  26.     }  
  27.     @Override  
  28.     public int onStartCommand(Intent intent, int flags, int startId) {  
  29.         return super.onStartCommand(intent, flags, startId);  
  30.     }  
  31.     /**  
  32.      *   
  33.      * @author Administrator  
  34.      * 线程用来改变seekbar进度的大小  
  35.      *  
  36.      */  
  37.     class UpdateProgress implements Runnable  
  38.     {  
  39.         @Override  
  40.         public void run() {  
  41.             if (isUpdate) {  
  42.                   size+=10;  
  43.                    if (size>100) {  
  44.                     size=0;  
  45.                 }  
  46.                    handler.sendEmptyMessage(0);  
  47.             }  
  48.         }  
  49.     }  
  50.     /**  
  51.      * 调用更新相应方法,更新进度条  
  52.      */  
  53.     Handler handler=new Handler()  
  54.     {  
  55.         public void handleMessage(android.os.Message msg) {  
  56.             /**  
  57.              * 直接调用activity对象里面的方法  
  58.              */  
  59.             if (activity!=null) {  
  60.                 activity.updateBar(size);  
  61.             }  
  62.               
  63.             /**  
  64.              * 使用接口回调  
  65.              */  
  66. //          if (listener!=null) {  
  67. //              listener.updateBar(size);  
  68. //          }  
  69.             handler.postDelayed(updateProgress, TIME);  
  70.         };  
  71.     };  
  72.       
  73.     /**  
  74.      * 停止更新  
  75.      */  
  76.     public void stopUpdateProgress()  
  77.     {  
  78.         isUpdate=false;  
  79.     }  
  80.     /**  
  81.      * 开启更新  
  82.      */  
  83.     public void startUpdateProgress()  
  84.     {  
  85.           
  86.         if (!isUpdate) {  
  87.             handler.post(updateProgress);  
  88.         }  
  89.         isUpdate=true;  
  90.     }  
  91.     public void onDestroy() {  
  92.         isUpdate=false;  
  93.     };  
  94.       
  95.     /**  
  96.      *   
  97.      * @param activity  
  98.      * 初始化MainActivity对象  
  99.      */  
  100.     public void setMainActivity(MainActivity activity)  
  101.     {  
  102.         this.activity=activity;  
  103.     }  
  104.     /**  
  105.      *   
  106.      * @param listener  
  107.      * 初始化UpdateProgressListener对象  
  108.      */  
  109.     public void setOnProgressBarListener(UpdateProgressListener listener)  
  110.     {  
  111.         this.listener=listener;  
  112.     }  
  113.       
  114.     /**  
  115.      *   
  116.      * @author Administrator  
  117.      * 使用类部类,返回当前service的实例,用于activity,调用service的各种方法  
  118.      *  
  119.      */  
  120.     class MyBuild extends Binder  
  121.     {  
  122.         public MyService getMyService()  
  123.         {  
  124.             return MyService.this;  
  125.         }  
  126.     }  
  127.       
  128.   
  129. }  


service里面最重要的就是,最下面我们的MyBuild类部类了,通过它的getMyService方法,获取service的实例

该类的实例实在onBind时候,我们返回给activity的。



接口:

[html]  view plain  copy
  1. package com.hck.bindservice;  
  2.   
  3. public interface UpdateProgressListener {  
  4.  public void updateBar(int size);  
  5. }  


一个简单接口,用于service回调activity



上面是使用 bindService来启动service的,那么如果我们使用startService启动service时候,上面的办法就不行了。

因为onBind不会执行,我们获取不到IBinder实例。这个时候,我们可以使用设计模式的观察者模式来处理。

其它不清楚,还有什么比较好的办法没有,我是没有想到,有知道的朋友,请告知,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值