首页 > 代码库 > 绑定Service并与之通信

绑定Service并与之通信

这个例程有三个按钮bindButton、unbindButton、getServiceStatusButton

分别是绑定Service、解除绑定、获取Service状态


BindServiceTest.java  在Activity中绑定本地Service,并获取Service的运行状态

public class BindServiceTest extends Activity {

	Button bindButton,unbindButton,getServiceStatusButton;
	
	// 保持所启动的Service的IBinder对象
	BindService.MyBinder binder;
	
	// 定义一个ServiceConnection对象
	private ServiceConnection conn = new ServiceConnection(){
		@Override
		// 当该Activity与Service连接成功时回调该方法
		public void onServiceConnected(ComponentName name, IBinder service) {
			System.out.println("--Service Connected--");
			binder = (BindService.MyBinder) service;
		}
		// 当该Activity与Service断开连接时回调该方法
		@Override
		public void onServiceDisconnected(ComponentName name) {
			System.out.println("--Service Disconnected--");
			
		}
	};		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		bindButton = (Button)findViewById(R.id.bind);
		unbindButton = (Button)findViewById(R.id.unbind);
		getServiceStatusButton = (Button)findViewById(R.id.getServiceStatus);
		final Intent intent = new Intent();
		intent.setAction("crazyit.service.BIND_SERVICE");
		bindButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				bindService(intent, conn, Service.BIND_AUTO_CREATE);
			}
		});
		unbindButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				unbindService(conn);
			}
		});
		getServiceStatusButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Toast.makeText(BindServiceTest.this,
						"Service的count值为"+ binder.getCount(), 
						Toast.LENGTH_SHORT).show();
			}
		});
		
	}
}

BindService.java  继承Service的子类,实现onBind()方法,并让该方法返回一个可访问该Service状态数据的IBinder对象,该对象将被传给该Service的访问者

public class BindService extends Service {

	private int count;
	private boolean quit;
	// 定义onBinder方法所返回的对象
	private MyBinder binder = new MyBinder();
	// 通过继承Binder来实现IBinder类
	public class MyBinder extends Binder{
		public int getCount(){
			// 获取Service的运行状态:count
			return count;
		}
	}
	// 必须实现的方法,绑定该Service时回调该方法
	@Override
	public IBinder onBind(Intent intent) {
		System.out.println("Service is Binded");
		// 返回IBinder对象
		return binder;
	}
	// Service被创建时回调该方法。
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		System.out.println("Service is Created");
		new Thread(){
			@Override
			public void run() {
				while(!quit){
					try{
						Thread.sleep(1000);
					}catch(InterruptedException e){
						e.printStackTrace();
					}
					count++;
				}
				
			}
		}.start();
	}
	// Service被断开连接时回调该方法
	@Override
	public boolean onUnbind(Intent intent) {
		System.out.println("Service is onUnbinded");
		return true;
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		this.quit = true;
		System.out.println("Service is Destroyed");
	}
}
manifest文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="crazyit.bindservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="crazyit.bindservice.BindServiceTest"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 配置一个Service组件 -->
		<service android:name=".BindService">
			<intent-filter>
				<!-- 为该Service组件的intent-filter配置action -->
				<action android:name="crazyit.service.BIND_SERVICE" />
			</intent-filter>	
		</service>
    </application>

</manifest>



绑定Service并与之通信