Service
- 实质:提供了一种不启动前台界面、让你在后台执行一些运算的途,方便挂起后台运行
- 后台运行,无界面,优先级高于activity
- 四大组件运行在主线程,不能用来做耗时操作;可以在服务中开一个线程,在线程中进行操作
- 类型
- 本地服务.应用程序内部,startService/stopService, bindService
- 远程服务.手机内部应用程序之间
- 都需要定义IBinder接口
- StartService
- BindService
- 特点:通过IBinder接口实例,返回一个ServiceConnection对象给启动源,通过后者的方法可以得到Service对象
- 定义一个类继承Service,需要进行注册,载xml文件中
<service android:name="包+类"></service>
- 实例
MyBinderService service;
ServiceConnection conn = new ServiceConnection(){
onServiceDisconnected(ComponentName name);
onServiceConnected(ComponentName name, IBinder binder) {
service = ((Mybinder)binder).getService();
}
}
Intent intent = new Intent(MainActivity.this, MyBinderService.class);
bindService(intent, conn, Service.BIND_AUTO_CREATE);
unbindService(conn);
startService(intent);
public class MyBinder extends Binder {
public MyBindService getService() {
return MyBinderService.this;
}
}
public IBinder onBind(Intent intent) {
return new MyBinder();
}