Services
*在實(shí)際運(yùn)行中同樣的Service的確只能有一個(gè)。
Services有兩種啟動(dòng)形式:
-
Started:其他組件調(diào)用startService()方法啟動(dòng)一個(gè)Service。一旦啟動(dòng),Service將一直運(yùn)行在后臺(tái)(run in the background indefinitely)即便啟動(dòng)Service的組件已被destroy。通常,一個(gè)被start的Service會(huì)在后臺(tái)執(zhí)行單獨(dú)的操作,也并不給啟動(dòng)它的組件返回結(jié)果。比如說(shuō),一個(gè)start的Service執(zhí)行在后臺(tái)下載或上傳一個(gè)文件的操作,完成之后,Service應(yīng)自己停止。
- 開(kāi)啟方式 :startService()? SwipeActivity.this.startService(new Intent(SwipeActivity.this, FindCardService.class));
- 結(jié)束方式1: SwipeActivity.this.stopService(new Intent(SwipeActivity.this, FindCardService.class));
- 結(jié)束方式2: stopSelf(); // 繼承Service的子類內(nèi)部調(diào)用
- 生命周期: onCreate() --> onStartCommand() --> onDestroy() // 如果Service已經(jīng)啟動(dòng),再次startService(),只會(huì)調(diào)用onStartCommand()方法,控件銷毀時(shí),記得解綁
-
Bound:其他組件調(diào)用bindService()方法綁定一個(gè)Service。通過(guò)綁定方式啟動(dòng)的Service是一個(gè)client-server結(jié)構(gòu),該Service可以與綁定它的組件進(jìn)行交互。一個(gè)bound service僅在有組件與其綁定時(shí)才會(huì)運(yùn)行(A bound service runs only as long as another application component is bound to it),多個(gè)組件可與一個(gè)service綁定,service不再與任何組件綁定時(shí),該service會(huì)被destroy。
- 開(kāi)啟方式:bindService() SwipeActivity.this.bindService(new Intent(SwipeActivity.this, FindCardService.class), connection, BIND_AUTO_CREATE);
- 結(jié)束方式:unbindService() SwipeActivity.this.unbindService(connection); // 解綁只能進(jìn)行一次,不然會(huì)出現(xiàn)崩潰:?Service not registered
- 生命周期: onCreate() --> onBind() --> onDestroy(); // 如果Service已經(jīng)啟動(dòng),再次bindService(),沒(méi)效果
- 使用如下:
綁定:
findViewById(R.id.bangding).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {SwipeActivity.this.bindService(new Intent(SwipeActivity.this, FindCardService.class), connection, BIND_AUTO_CREATE);}});解綁:
@Overrideprotected void onDestroy() {super.onDestroy();if (mBound) {SwipeActivity.this.unbindService(connection);}}Service:
@Nullable@Overridepublic IBinder onBind(Intent intent) {CoreLog.d(TAG, "FindCardService -- onBind()");return mFindCardBinder;}private FindCardBinder mFindCardBinder = new FindCardBinder();public class FindCardBinder extends Binder { public void startFindCard() { }}額外情況:
如果使用了bindService和startService混合使用會(huì)是什么情況?
1.stopService()會(huì)失效,即使使用了stopService(),不會(huì)調(diào)用onDestory()方法。
其他的,會(huì)按照各自的生命周期來(lái)走。
2.當(dāng)控件都解綁了,才會(huì)調(diào)用onDestory()方法。
3.在Service每一次的開(kāi)啟關(guān)閉過(guò)程中,只有onStart可被多次調(diào)用(通過(guò)多次startService調(diào)用),其他onCreate,onBind,onUnbind,onDestory在一個(gè)生命周期中只能被調(diào)用一次。也就是說(shuō)Activity A 在onCreate()方法中bindService,正常調(diào)用onBind(),但沒(méi)有在onDestory()方法中unbindService。Activity B在onCreate()方法中bindService,但沒(méi)有調(diào)用onBind()方法了。
轉(zhuǎn)載于:https://www.cnblogs.com/H-BolinBlog/p/6183559.html
總結(jié)
- 上一篇: Date Picker和UITool B
- 下一篇: ajaxfileupload踩过的坑