Service
主要用於在後台處理一些耗時的運算,或者去執行某些需要長期運行的任務。必要的時候可以在APP退出的情況下,讓Service在後台繼續保持運行狀態。而Service與其他組件交流一般是使用廣播Broadcast的方式。在其他組件註冊要接收的廣播訊息,就可以接收到Service發出廣播訊息資料。以下是一個Service的基本架構
public class MyService extends Service {
public static final String TAG = "MyService";
public class LocalBinder extends Binder {
public MyService getService()
{
return MyService.this;
}
}
private final IBinder mBinder = new LocalBinder();
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
跟Activty一樣,Service也需要至AndroidMainfest.xml中宣告,才可以使用
<service
android:name=".service.SampleService"
android:enabled="true" />
需注意的一點是,Service本身並非一個獨立的Process,也不會脫離Main Thread獨立運作,如果需要做長時間的運算,仍需在Service內產生Thread。
Client利用Context.bindService()來建立與service的聯繫。之後Android系統會呼叫Service中的onBind()方法,返回一個用來與Service交互的IBinder,此聯繫的動作是非同步的,呼叫bindService()後並不會返回IBinder給Client,要接收IBinder,Client必需建立一個ServiceConnection的實例並傳給bindService();ServiceConnection包含一個回傳方法,系統利用這個方法來傳遞要返回的IBinder。使用範例如下
MyService myService;
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent syncServiceIntent = new Intent(this, MyService.class);
bindService(syncServiceIntent, myServiceConnection, BIND_AUTO_CREATE);
}
private final ServiceConnection myServiceConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("RunStep", "服務程式已連結");
myService = ((MyService.LocalBinder) service).getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d("RunStep", "服務程式已斷開")
myService = null;
}
};