7、认识 Android Service

1、使用Service
什么是service,在很多时候我们的程序不需要可以与用户交互的界面,他只需要在后台运行做一些事务的处理,比如socket长连
接,这就要使用service

创建service:
右边菜单new Service
如何启动service
startService(new Intent(MainActivity.this, 类.class/*MyService.class*/));
停止服务
stopService(new Intent(MainActivity.this, 类.class/*MyService.class*/));


public int onStartCommand(Intent intent, int flags, int startId)
执行完startservice调用


2、绑定Service

bindService(intent,this, Context.BIND_AUTO_CREATE);

@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//服务被绑定成功后执行
}

@Override
public void onServiceDisconnected(ComponentName componentName) {
//服务所在的进程奔溃的时候或者被杀掉的时候调用
}


@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return new Binder();
}
3、Service的生命周期

public void onCreate()
public void onDestroy()
如果,同时启动服务并且绑定服务,那么必须同时停止服务,解除绑定,服务才可以停掉
如果说你的activity 与某个service进行绑定的话,那么在你退出activity的时候,服务会取消绑定(不求同世生但求同时死)
重复去执行启动服务的操作我们会发现onStartCommand会执行很多次,oncreate只会执行一次onStartCommand,只要执行startService(intent); 在内部就会执行onStartCommand

原文地址:https://www.cnblogs.com/NuoChong/p/11990152.html