Activity与Service通信之Bound Service

本文介绍如何在Android应用中使用BoundService实现Activity与Service间的通信。通过示例代码展示了如何创建和绑定Service,以及如何在Activity中获取Service提供的数据。

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

在开发Android应用时,经常有这样的需求,就是使用Service在后台执行耗时操作,当某一操作完成时或者需要将操作的进度显示在前台的Activity中。这就需要用到Activity与Service之间的通信。

其实,Activity与Service之间的通信有很多方式,如果需求简单,直接可以使用Intent从Activity向Service传递数据,如果需要Service向Activity返回数据,可以使用如使用广播机制(BroadcastReceive),使用AIDL (Android Interface Definition Language),还有就是Bound Service。

下面的例子是使用Bound Service即绑定服务的方式实现两者之间的通信,直接看代码:

首先是Service:

/**
 * 
 */
package com.gufengxiachen.boundservice;

import java.util.Random;

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

/**
 * description:
 * @TODO
 * @author wustrive_2008
 * @date 2012-1-9
 */
public class LocalService extends Service{
	private final IBinder mBinder = new LocalBinder();
	private final Random mGenerator = new Random();
	
	 public class LocalBinder extends Binder {
	        LocalService getService() {
	           //在这里返回当前Service对象,在Activity中调用此方法后即可得到Service的引用
	            return LocalService.this;
	        }
	 }
	 
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return mBinder;
	}
	
	//这个是用来测试的方法
	 public int getRandomNumber() {
	      return mGenerator.nextInt(100);
	 }

}

下面是Activity的代码:

package com.gufengxiachen.boundservice;

import com.gufengxiachen.boundservice.LocalService.LocalBinder;

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.Toast;

public class BoundServiceActivity extends Activity {
	
	LocalService mService;
    boolean mBound = false;
    private Button button;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //这里是最重要的代码,也可以放到onStart()方法中,即绑定服务
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
      
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new onClickListener());
    }
    
    @Override
    protected void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
    	 
    }
    
    @Override
    protected void onStop() {
    	// TODO Auto-generated method stub
    	super.onStop();
    	 if (mBound) {
             unbindService(mConnection);
             mBound = false;
         }
    }
    
    class onClickListener implements OnClickListener{
    	@Override
    	public void onClick(View v) {
    		// TODO Auto-generated method stub
    		//Toast.makeText(BoundServiceActivity.this, "fdsafd", Toast.LENGTH_LONG).show();
    		 if (mBound) {
    	            int num = mService.getRandomNumber();
    	            Toast.makeText(BoundServiceActivity.this, "number: " + num, Toast.LENGTH_SHORT).show();
    	        }
    	}
    }
    
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}

最后不要忘了在AndroidManifest.xml文件中注册Service。