Service作為Android四大組件之一,在Android系統(tǒng)中有著居住輕重的位置。
Service有兩種啟動(dòng)方式,第一種就是通過Context.startService來啟動(dòng),此時(shí)的Service為啟動(dòng)狀態(tài)的Service,第二種通過bindService啟動(dòng)。
對于第一種情況,在通過StartService啟動(dòng)之后執(zhí)行onCreate-onCommand,這個(gè)Service便會(huì)一直運(yùn)行下去,直到調(diào)用了Context.stopService或者Service自身由于任務(wù)完成調(diào)用了selfDestroy。而對于第二種情況的,Service在被第一個(gè)宿主綁定的時(shí)候啟動(dòng),依次執(zhí)行onCreate-onBind,多個(gè)宿主可以同時(shí)綁定一個(gè)Service,直到最后一個(gè)宿主unbind該Service之后該Service才會(huì)被Destroy。
下面為通過第一種情況來實(shí)現(xiàn)的Service,即啟動(dòng)狀態(tài)的Service:
public class StartableService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
直接繼承Service,實(shí)現(xiàn)onBind方法,這邊是一個(gè)最簡單的Service,這個(gè)Service什么都沒有做。但這樣的Service是無法被啟動(dòng)的,我們還需要再M(fèi)anifest文件中進(jìn)行Service的申明,就像申明Activity一樣:
<service android:name=".StartableService"/>
如此一來這個(gè)Service便可以被啟動(dòng)了
StartableActivity
點(diǎn)擊“啟動(dòng)StartableService”

Logcat

image.png
接下來我們通過客戶端與Service進(jìn)行通信,Service代碼修改為
public class StartableService extends Service {
String TAG = getClass().getSimpleName();
MyBinder mBinder = new MyBinder();
public class MyBinder extends Binder{
public StartableService getService(){
return StartableService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
...
客戶端代碼
public class StartableServiceActivity extends Activity {
private Intent mIntent;
StartableService service;
ServiceConnection conn = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
StartableService.MyBinder binder = (StartableService.MyBinder) iBinder;
service = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startable_service);
mIntent = new Intent(this,StartableService.class);
findViewById(R.id.btnStartService).setOnClickListener(v->{
bindService(mIntent,conn,Service.BIND_AUTO_CREATE);
});
findViewById(R.id.btnStopService).setOnClickListener(v->{
if (service!=null) {
service = null;
unbindService(conn);
}
});
findViewById(R.id.btnEvokeService).setOnClickListener(v->{
if (service!=null){
Toast.makeText(StartableServiceActivity.this,service.getInfo(),Toast.LENGTH_LONG).show();
}
});
}
}

image.png