17、從頭學Android之Service初步二

在上一篇,我們學習了通過startService來啓動Service,由於篇幅過長,所以這一篇是接上一篇的

二、bindService方法啓動Service

先看bindSerivce(Intent service,ServiceConnection conn,int flags)函數

參數說明:

service:通過該參數也就是Intent我們可以啓動指定的Service

conn:該參數是一個ServiceConnection對象,這個對角用於監聽訪問者(也可以說成是客戶端)與Service之間的連接情況,當訪問者與Service連接成功時將回調ServiceConnection對象的onServiceConnected(ComponentName name,Ibinder service)方法;如果斷開將回調onServiceDisConnected(CompontName name)方法

flags:指定綁定時是否自動創建Service。

步驟:

1、  新建一個類繼承於Service類,重寫onBind()、onCreate()、onUnBind()、onDestory()方法。再在這個類裏聲明一個Ibinder的子類對象用於提供於客戶端,同時可以定義一些成員變量,客戶端可以獲取到這個成員變量屬性

2、  在AndroidMainfest.xml文件中註冊這個Service

3、  在Activity裏通過bindService綁定Service

示例代碼:

 

package com.jiahui.serviceDemo;

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

public class MyService extends Service {

	private int count;

	private boolean quit;

	private MyBinder binder = new MyBinder();

	// 新建一個Binder對象用於提供給客戶端
	public class MyBinder extends Binder {

		public int getCount() {
			return count;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		System.out.println("----onBind-----");
		// 返回給客戶端一個Binder對象
		return binder;
	}

	@Override
	public void onCreate() {
		System.out.println("----onCreate-----");

		// 啓動一條線程修改成員變量屬性
		new Thread() {
			@Override
			public void run() {
				while (!quit) {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
					
					}
					count++;
				}
			}

		}.start();

	}

	@Override
	public void onDestroy() {
		this.quit = true;
		System.out.println("----onDestory-----");
		super.onDestroy();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		System.out.println("----onUnbind-----");
		return super.onUnbind(intent);
	}

}


 

 

MainActivty

package com.jiahui.serviceDemo;

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

public class MainActivity extends Activity {

	private Button btnBind;
	private Button btnUnBind;
	private Button btnGetData;

	MyService.MyBinder binder;
	// 定義一個ServiceConnection對象
	private ServiceConnection conn = new ServiceConnection() {

		// 當客戶端與Service斷開連接時
		@Override
		public void onServiceDisconnected(ComponentName name) {
			System.out.println("---onServiceDisconnected----");

		}

		// 當客戶端與Service建立連接時
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			System.out.println("---onServiceConnected----");
			binder = (MyService.MyBinder) service;
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		btnBind = (Button) findViewById(R.id.btnBind);
		btnUnBind = (Button) findViewById(R.id.btnUnBind);
		btnGetData = (Button) findViewById(R.id.btnGetData);
		final Intent intent = new Intent();
		intent.setAction("com.jiahui.myservice");

		btnBind.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// 綁定Service
				bindService(intent, conn, BIND_AUTO_CREATE);
			}
		});

		btnUnBind.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 解除綁定
				unbindService(conn);

			}
		});

		//獲取數據
		btnGetData.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 獲取數據
				Toast.makeText(MainActivity.this,
						"Service的 count值爲" + binder.getCount(),
						Toast.LENGTH_LONG).show();
			}
		});

	}
}


 

實現效果:

點擊”bindService”按鈕

點擊” 獲取Service裏的數據”按鈕

點擊“unBindService”按鈕

所以也可以通過上圖知道bindService的生命週期

bindService會經歷onCreate()-->onBind()-->onUnbind()-->onDestory

 

如何去理解這種通信方式?

我的理解是bindService這一方我們可以看作是客戶端,然後客戶端調用bindService()方法去綁定一個Service,Service給我們返回一個Binder對象用於客戶端與Serivce通信,而這個Binder對象我們可以在客戶端的ServiceConnection對象裏的一個onServiceConnected()方法取到這個Binder對象,這樣我們就也能取到Service裏的數據了

貼上一張圖更加方便大家理解:

所以總結:

bindService與startService 的區別:

1. 生命週期 : startService() 方式啓動 , Service 是通過接受 Intent 並且會經歷 onCreate()和 onStart() 。當用戶在發出意圖使之銷燬時會經歷 onDestroy () ,而 bindService () 方

式啓動 , 與 Activity 綁定的時候 , 會經歷 onCreate() 和 onBind () , 而當 Activity 被銷燬的時候, Service 會先調用 onUnbind () 然後是 onDestroy () 。

2. 控制方式 :前者的控制方式需要使用固定的方法,對 Service 進行單一的操作。而後者

由於與 Activity 綁定 , 不用考慮其生命週期問題 , 並且從發送 Intent 的被動操作 , 變爲可以主動對 Service 對象進行操作,我們甚至可以建立一個 Handler 類,對 Service 進行相關的操作。大大加強了 Service 的靈活性、可操作性。

 

總結 : 對於簡單的應用 startService() 啓動方式能帶來更少的代碼 , 簡單的操作 。 對於複雜的應用 bindService () 方式,雖然帶來的更多的編碼,但同時也帶來了更好的可操作性,使其使用起來更像 Activity 。

 如需轉載引用請註明出處:http://blog.csdn.net/jiahui524

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章