標籤:service android
從運行模式來看,Android的服務元件沒有運行在獨立的進程或線程中,而是和Android其他組件一樣運行在進程的主線程中。所以直接在服務元件中同步執行耗時操作,將會阻塞主線程。
像Service的子類IntentService,完成建構函式和onHandleIntent(Intent intent)方法,然後就可以通過startService(intent)發送執行命令,IntentService接收到首個命令時,IntentService完成啟動,並觸發一個後台線程,然後將命令放入隊列。IntentService會順序執行這些命令,並同時為每一條命令在後台線程上調用onHandleIntent(intent)的方法。當執行完隊列的所有命令後,服務也隨即停止並被銷毀。PS:IntentService是一種non-sticky服務。
non-sticky服務:當服務自己認為已經完成任務時,會調用stopSelf()或者stopSelf(int)方法告訴Android任務已經完成,以結束服務。
sticky服務:服務會持續運行,直到某個組件調用Context.stopService(Intent)讓它停止。
Service的生命週期
一、Context.startService
當初次開機服務時,會依次調用onCreate()和onStart(),如果服務已經被建立,再調用startService(intent)
就只會執行onStart()。Intent傳遞過來的參數可以在onStartCommand()方法中進行處理。主動結束時執行
stopSelf()方法,被動結束調用Context.stopService()方法,然後再執行onDestroy()。
二、Context.bindService
如果用戶端想持續串連服務,擷取服務執行個體可以使用綁定服務這種方式。
同樣首次建立服務時,會調用onCreate(),然後onBind方法會構造一個IBinder對象返回給調用者,建立通訊連
接,調用者通過重寫ServiceConnection類中的onServiceConnected()方法可以擷取此IBinder對象。通過
onUnBind解除綁定服務,然後再執行onDestroy()。綁定服務的組件在銷毀前應解除綁定,否則會造成記憶體泄
露。
部分代碼如下:
Service端
public class MyService extends Service { private static final String TAG = "MyService"; private MyBinder mBinder = new MyBinder(); // 建立一個Binder對象,通過onBinder返回給調用者,調用者再通過此對象得到該服務執行個體 @Override public IBinder onBind(Intent intent) { Log.e(TAG, "start IBinder~~~"); return mBinder; } @Override public void onCreate() { Log.e(TAG, "start onCreate~~~"); super.onCreate(); } @Override public void onDestroy() { Log.e(TAG, "start onDestroy~~~"); super.onDestroy(); } @Override public boolean onUnbind(Intent intent) { Log.e(TAG, "start onUnbind~~~"); return super.onUnbind(intent); } //為服務建立一個公用方法,用於測試 public String test(){ System.out.println("test"); } public class MyBinder extends Binder{ MyService getService(){ return MyService.this; } } }
調用端:
public class ServiceDemo extends Activity { private ServiceConnection mServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder service) { mMyService = ((MyService.MyBinder)service).getService(); mMyService.test(); // 直接調用服務執行個體的公用方法 } public void onServiceDisconnected(ComponentName name) { } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent i = new Intent(); i.setClass(ServiceDemo.this, MyService.class); mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE); } }
Android Service 筆記