Service與Activity通信

一:思想

在Android中,Activity的類可以看成是“可見”的邏輯處理類,擁有用戶界面與用戶進行互動操作,但如果這個Acitvity失去了“焦點”,則它的邏輯處理隨即停止,那樣如果我們需要進行一些後臺類的操作,既與用戶當前操作的焦點無關,可以在背後一直運行,爲相應的應用程序提供服務,Android中這種邏輯處理類稱爲Service。一般繼承自Service類。

Service類是沒有用戶界面,但只作爲一種後臺邏輯處理,爲表層Activity提供相應的服務操作,所以Service類處理後的數據要交回給Activity,Activity也要獲得Service的服務邏輯,即兩者之間要進行交互。而這個交互過程如下:

1、Service類中要創建一個內部類。繼承自Binder,因爲在Service這個父類中,Onbind方法返回一個IBinder接口的返回值,而Binder是IBinder接口的一個實現。

2、繼承自IBinder類的內部類,只需要實現一個返回Service自身對象的功能的方法即可。

3、在Activity中通過bindService方法與對應的Service進行綁定,一旦執行這個方法,則系統自動調用Service類中的onbind方法,這裏就會返回一個IBinder類返回值,也就是Service創建的內部類對象。

4、在Activity中創建一個ServiceConnection對象,作爲參數傳入上面的bindService方法中。這裏自動調用Onbind方法就會將Service返回的IBinder類的返回值傳入到ServiceConnection中的onServiceConnected方法的參數中。這個方法只需要實現IBinder返回值中的返回Service自身的方法賦值到Activity的一個參數即可。

5、要在AndroidManifest.xml文件中註冊Service。

6、注意Service的真正啓動其實是在調用Service的線程結束後,例如在Activity中的OnCreate方法中執行startService或者bindService等操作,Service也只在OnCreate方法完成後才真正開始執行。

二:例子代碼:

1、Service類

ServiceTestpublicclass ServiceTest extends Service {private MyBinder binder = new MyBinder();@Overridepublic IBinder onBind(Intent intent) {Log.i("demo", "onbind");return binder;}class MyBinder extends Binder{public ServiceTest getService(){return ServiceTest.this;}}}

2、Activity類

 ServiceTestpublicclass BlogTestActivity extends Activity {/** Called when the activity is first created. */private ServiceTest Myservice = null;@Overridepublicvoid onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Intent bindService = new Intent(BlogTestActivity.this,ServiceTest.class);startService(bindService);this.bindService(bindService, connection, Context.BIND_AUTO_CREATE);}ServiceConnection connection = new ServiceConnection() {@Overridepublicvoid onServiceDisconnected(ComponentName name) {Myservice = null;}@Overridepublicvoid onServiceConnected(ComponentName name, IBinder service) {Log.i("demo", "連接了Server!");Myservice = ((ServiceTest.MyBinder) service).getService();}};}

轉自:http://blog.csdn.net/hahashui123/article/details/7341950

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