您的位置:首页 > 其它

Service详解

2016-08-26 16:35 316 查看
Service生命周期:

如图:



代码测试:

继承Swevice:

public class Myservice extends Service {

@Override
public void onCreate() {
super.onCreate();
Log.i("woyaokk", "====================onCreate==============");
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i("woyaokk","====================onBind==============");
return new MyBinder();
}

@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
Log.i("woyaokk", "====================onBind==============");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("woyaokk","====================onStartCommand==============");
return super.onStartCommand(intent, flags, startId);
}

@Override
public boolean onUnbind(Intent intent) {
Log.i("woyaokk","====================onUnbind==============");
return super.onUnbind(intent);
}

@Override
public void onDestroy() {
Log.i("woyaokk","====================onDestroy==============");
super.onDestroy();
}

class MyBinder extends Binder {
/**
* 获取Service的方法
*/
public Myservice getService(){
return Myservice.this;
}
}

}

注册:

<service android:name=".Myservice"></service>

启动:

Intent intent=new Intent(MainActivity.this,Myservice.class);
MainActivity.this.startService(intent);

停止:
Intent intent=new Intent(MainActivity.this,Myservice.class);
MainActivity.this.stopService(intent);

当使用两次启动方法,一次停止方法,返回:



由此可知:通过startService方法启动Service则会调用OnCreate方法和OnStartCommand方法,并且多次调用startService方法只会调用由此OnCreate,但会掉用多次onStartCommand,销毁时调用onDestory

绑定:

ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 建立连接
Myservice.MyBinder binder = (Myservice.MyBinder) service;
myService = binder.getService();
}

@Override
public void onServiceDisconnected(ComponentName name) {
// 连接断开
}
};
Intent intent=new Intent(MainActivity.this,Myservice.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
解绑:
unbindService(serviceConnection);

声明周期:



由此可知:通过启动通过绑定启动Service调用onCreate和onBind方法,解绑时调用onUnbind和onDestory方法;

注意:

Service和Thread本质上没有半毛钱关系,Service同样运行在主线程中,所以一样不能执行耗时操作,如果需要执行耗时操作,可以开启异步线程或者继承IntentService
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Service