android中service分两种,local/remote;
local service为本地同acivity进程内service,local service随activity同时结束生命;
remote service与activity在不同进程中,其生命的结束与activity生死无关;
service使用时,需要在AndroidManifest.xml进行声明,process=”:remote”即为remote service
<service android:name="com.qijie.studyservice.MyLocalService"/>
<service android:name="com.qijie.studyservice.MyRemoteService" android:process=":remote"/>
Service的实现需继承android.app.Service,重载onBind方法:
@Override
public IBinder onBind(Intent arg0) {
android.os.Messenger messenger = new Messenger (new Handler() {
@Override
public void handleMessage(Message msg) {
//消息处理;
}
);
return messenger.getBinder();
}
android.os.Messenger可以实现activity与Service的通信,但对于local Service来讲,这样做显然相对麻烦,因为local Service与Activity在相同进程,我们可以在重载onBind方法时返回一个继承自Binder的对象即可;
@Override
public IBinder onBind(Intent arg0) {
return new LocalBinder();
}
public class LocalBinder extends Binder {
public LocalService getService() {
return LocalService.this;
}
}
service调用有两种方式:
startService/stopService方式,用于启动和停止服务运行,但无法与Service进行通信;
bindService/unbindService方式,可以实现activity与Service的数据通信,注意在activity退出时必须调用unbindService方法与Service解除绑定;
- remote service调用过程:
startService:
->onCreate()->onStart();
stopService:
if not bind then
onDestory();
else if was bind then
just return;
bindService:
onCreate()->onBind();
unbindService:
if not start service then
onUnbind()->onDestory();
else if started service then
just onUnbind();