startService和binderService的混合使用时的生命周期
创建MyService类
创建一个MyService类继承与Service:
public class MyService extends Service {
@Override
public void onCreate() {
Log.i(getClass().getSimpleName(),"onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(getClass().getSimpleName(),"onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i(getClass().getSimpleName(),"onDestory");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
Log.i(getClass().getSimpleName(),"onBind");
return new MyBinder();
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(getClass().getSimpleName(),"onUnbind");
return super.onUnbind(intent);
}
public class MyBinder extends Binder{
MyService getService(){
return MyService.this;
}
}
}
绑定和开启MyService
startService和binderService:
public class MainActivity extends Activity implements View.OnClickListener {
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myService = ((MyService.MyBinder)service).getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
private MyService myService;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn1).setOnClickListener(this);
findViewById(R.id.btn2).setOnClickListener(this);
findViewById(R.id.btn3).setOnClickListener(this);
findViewById(R.id.btn4).setOnClickListener(this);
}
@Override
public void onClick(View view) {
intent = new Intent(MainActivity.this,MyService.class);
switch (view.getId()) {
case R.id.btn1:
startService(intent);
break;
case R.id.btn2:
bindService(intent,conn,BIND_AUTO_CREATE);
break;
case R.id.btn3:
stopService(intent);
break;
case R.id.btn4:
unbindService(conn);
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
stopService(intent);
unbindService(conn);
}
}
- startService ===>bindService ==>stopService ==>unbindService;
stopService并没有调用Service中的任何方法,因为bindService还没有与MyService取消绑定 - bindService ==>startService ==>stopService ==>unbindService
stop依旧没有调用Service中的方法; - startService ==>bindService ==>unbindService ==>stopService
到这一步我们可以知道,最后与Service解除绑定/停止服务的那个方法,才会执行onDestory,