Android Service与Activity之间通信的方式 其中包含了回调机制的实现方法

《》该文章摘自http://blog.csdn.net/xiaanming/article/details/8703708再次注明出处,感谢博主的劳动

《》在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务,所以在我们实际开发中,

就会常常遇到Activity与Service之间的通信,我们一般在Activity中启动后台Service,通过Intent来启动,

Intent中我们可以传递数据给Service(通过Intent的Extra属性就可以),而当我们Service执行某些操作之后想要更新UI线程,我们应该怎么做呢?

接下来我就介绍两种方式来实现Service与Activity之间的通信问题:

 

《》通过Binder对象进行通信

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

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

 

<span style="font-family: System;">package com.example.communication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MsgService extends Service {
    /**
     * 进度条的最大值
     */
    public static final int MAX_PROGRESS = 100;
    /**
     * 进度条的进度值
     */
    private int progress = 0;

    /**
     * 增加get()方法,供Activity调用
     * @return 下载进度
     */
    public int getProgress() {
        return progress;
    }

    /**
     * 模拟下载任务,每秒钟更新一次
     */
    public void startDownLoad(){
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                while(progress < MAX_PROGRESS){
                    progress += 5;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                }
            }
        }).start();
    }


    /**
     * 返回一个Binder对象
     */
    @Override
    public IBinder onBind(Intent intent) {
        return new MsgBinder();
    }
    
    public class MsgBinder extends Binder{
        /**
         * 获取当前Service的实例
         * @return
         */
        public MsgService getService(){
            return MsgService.this;
        }
    }

}</span>

上面的代码比较简单,注释也比较详细,最基本的Service的应用了,相信你看得懂的,我们调用startDownLoad()方法来模拟下载任务,然后每秒更新一次进度,但这是在后台进行中,我们是看不到的,所以有时候我们需要他能在前台显示下载的进度问题,所以我们接下来就用到Activity了

Intent intent = new Intent("com.example.communication.MSG_ACTION");  
bindService(intent, conn, Context.BIND_AUTO_CREATE);

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

 

<span style="font-family: System;">    ServiceConnection conn = new ServiceConnection() {
        
        @Override
        public void onServiceDisconnected(ComponentName name) {
            
        }
        
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个MsgService对象
            msgService = ((MsgService.MsgBinder)service).getService();
            
        }
    };</span>

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

<span style="font-family: System;">package com.example.communication;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
    private MsgService msgService;
    private int progress = 0;
    private ProgressBar mProgressBar;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        //绑定Service
        Intent intent = new Intent("com.example.communication.MSG_ACTION");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        
        
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
        Button mButton = (Button) findViewById(R.id.button1);
        mButton.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                //开始下载
                msgService.startDownLoad();
                //监听进度
                listenProgress();
            }
        });
        
    }
    

    /**
     * 监听进度,每秒钟获取调用MsgService的getProgress()方法来获取进度,更新UI
     */
    public void listenProgress(){
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                while(progress < MsgService.MAX_PROGRESS){
                    progress = msgService.getProgress();
                    mProgressBar.setProgress(progress);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                
            }
        }).start();
    }
    
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            
        }
        
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个MsgService对象
            msgService = ((MsgService.MsgBinder)service).getService();
            
        }
    };

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }


}</span><span style="font-family: simsun;">
</span>

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

public interface OnProgressListener {
    void onProgress(int progress);
}

MsgService的代码有一些小小的改变,为了方便大家看懂,我还是将所有代码贴出来

 

<span style="font-family: System;">package com.example.communication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MsgService extends Service {
    /**
     * 进度条的最大值
     */
    public static final int MAX_PROGRESS = 100;
    /**
     * 进度条的进度值
     */
    private int progress = 0;
    
    /**
     * 更新进度的回调接口
     */
    private OnProgressListener onProgressListener;
    
    
    /**
     * 注册回调接口的方法,供外部调用
     * @param onProgressListener
     */
    public void setOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListener = onProgressListener;
    }

    /**
     * 增加get()方法,供Activity调用
     * @return 下载进度
     */
    public int getProgress() {
        return progress;
    }

    /**
     * 模拟下载任务,每秒钟更新一次
     */
    public void startDownLoad(){
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                while(progress < MAX_PROGRESS){
                    progress += 5;
                    
                    //进度发生变化通知调用方
                    if(onProgressListener != null){
                        onProgressListener.onProgress(progress);
                    }
                    
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                }
            }
        }).start();
    }


    /**
     * 返回一个Binder对象
     */
    @Override
    public IBinder onBind(Intent intent) {
        return new MsgBinder();
    }
    
    public class MsgBinder extends Binder{
        /**
         * 获取当前Service的实例
         * @return
         */
        public MsgService getService(){
            return MsgService.this;
        }
    }

}</span>

Activity中的代码如下

 

<span style="font-family: System;">package com.example.communication;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
    private MsgService msgService;
    private ProgressBar mProgressBar;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        //绑定Service
        Intent intent = new Intent("com.example.communication.MSG_ACTION");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        
        
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
        Button mButton = (Button) findViewById(R.id.button1);
        mButton.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                //开始下载
                msgService.startDownLoad();
            }
        });
        
    }
    

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            
        }
        
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个MsgService对象
            msgService = ((MsgService.MsgBinder)service).getService();
            
            //注册回调接口来接收下载进度的变化
            msgService.setOnProgressListener(new OnProgressListener() {
                
                @Override
                public void onProgress(int progress) {
                    mProgressBar.setProgress(progress);
                    实际上在这里改变一个UI线程中的进度条,会有点问题,因为这个方法实际上是在Service中的那条新线程中调用的(仔细想想为什么),
所以不能够在其他线程中改变UI线程中的view组件,但是这里却没有报错,可能是进度条有不同的地方吧! } }); } }; @Override
protected void onDestroy() { unbindService(conn); super.onDestroy(); } } </span>

用回调接口是不是更加的方便呢,当进度发生变化的时候Service主动通知Activity,Activity就可以更新UI操作了

编者注:实际上,上面的这段代码非常的好,一方面我们可以知道  回调监听的机制到底怎么实现 ,

另一方面我们是通过IBinder,在Activity中直接获得了整个的Service的对象,这样有两个好处,

1、我们能够获得Service对象中的所有的数据的情况 ;

2 、由于我们可以通过Service对象调用Service子类中的方法,所以,我们可以在Activity需要的时候调用Service对象的任何方法,

也就是说,像上面一样,我们可以通过单击一个Activity中的一个按钮来开始Service中的后台任务,而不是在绑定Service的时候,

这样一来,我们就可以先在Activity中绑定一个Service,但是并不开始它的后台任务,在Activity的适当的时机(比如点击一个按钮)

在通过获得Service对象,开始后台任务,这样的话,整个逻辑就非常的清晰,简明。再次向作者表示感谢!

 《》我想通过使用Handler也可以实现,想一想吧!

《》通过BroadCaster进行通信——当Service中的消息需要通知更多的Activity时,会非常的有用

posted @ 2014-10-26 19:31  RoperLee  阅读(539)  评论(0)    收藏  举报