Service與Activity通訊

一:思想ide

在Android中,Activity的類能夠當作是「可見」的邏輯處理類,擁有用戶界面與用戶進行互動操做,但若是這個Acitvity失去了「焦點」,則它的邏輯處理隨即中止,那樣若是咱們須要進行一些後臺類的操做,既與用戶當前操做的焦點無關,能夠在背後一直運行,爲相應的應用程序提供服務,Android中這種邏輯處理類稱爲Service。通常繼承自Service類。ui

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

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

二、繼承自IBinder類的內部類,只須要實現一個返回Service自身對象的功能的方法便可。.net

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

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

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

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

二:例子代碼:blog

一、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;}}}

二、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

相關文章
相關標籤/搜索