1.生命周期
startService():onCreate() -> onStartCommand() -> onStart() (过时方法由onStartCommand()替代) -> onDestroy()
bindService():onCreate() -> onBind() -> onServiceConnected() -> onUnbind -> onDestroy()
onServiceDisconnected
只会在Service丢失时才会调用, 通常会在Service所在进程被迫终止时才会调用, 当Service重新运行时会再次调用onServiceConnected
方法
2.用startService()启动的service,退出activity()可以不stopService();如果不调用stopService()服务会一直在后台运行
用bindService()启动的service,退出activity()必须unbindService();如果不调用unbindService(),会报错
3.bindService()的代码示例:
public class MyService extends Service {
private final String TAG = "MainActivity";
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind" );
return new MyBinder();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand" );
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.e(TAG, "onStart" );
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(TAG, "onUnbind" );
return super.onUnbind(intent);
}
public String getString() {
return "你好 哈哈哈";
}
public class MyBinder extends Binder{
MyService getService() {
return MyService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate" );
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy" );
}
}
public class MainActivity extends Activity {
private MyServiceConnection conn;
private final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conn = new MyServiceConnection();
bindService(new Intent(this, MyService.class),conn, Context.BIND_AUTO_CREATE);
}
public class MyServiceConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService myService = ((MyService.MyBinder) service).getService();
String body = myService.getString();
Log.e(TAG, "onServiceConnected :"+body );
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, "onServiceDisconnected" );
}
}
@Override
protected void onDestroy() {
super.onDestroy();
stopService(new Intent(this, MyService.class));
unbindService(conn);
}
}