一、创建Service
public class TcpService extends Service {
public TcpService() {
}
@Override
public IBinder onBind(Intent intent) {
//返回工作的类
return new Mybind();
}
//工作的类,由onBind时返回
class Mybind extends Binder {
public void getString(){
Log.e("ServiceTest"," -----> getString");
}
}
}
二、调用
1、绑定(常用,需要ServiceConnection对象配合)
a)创建ServiceConnection对象
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mybind = (TcpService.Mybind) service;
mybind.getString(); //获取到getString方法
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
b)绑定语句
Intent bindService = new Intent(MainActivity.this,TcpService.class);
bindService(bindService,connection,BIND_AUTO_CREATE);
2、解除绑定
unbindService(connection);
3、开始服务(没啥用,不需要任何东西辅助)
Intent tcpService = new Intent(MainActivity.this,TcpService.class);
startService( tcpService );
4、停止服务(没啥用,不需要任何东西辅助)
Intent tcpService = new Intent(MainActivity.this,TcpService.class);
stopService( tcpService );
三、生命周期,主要有以下三个
@Override
public void onCreate() {
super.onCreate(); Log.e("ServiceTest"," -----> onCreate");
}
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
Log.e("ServiceTest"," -----> onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy(); Log.e("ServiceTest"," -----> onDestroy");
}