巩固一下基础,写的不好请多多包涵。
【服务的概念】
Service(服务)是一个一种可以在后台执行长时间运行操作而没有用户界面的应用组件。服务可由其他应用组件启动(如Activity),服务一旦被启动将在后台一直运行,即使启动服务的组件(Activity)已销毁也不受影响。
【了解的内容】
【1】Android四大组件都运行在主线程中
【2】Android系统会被每个应用创建一个进程还有一个线程(主线程)
进程优先级:前台进程>可视进程>服务进程>后台进程>空进程
【Service生命周期图】
【开启服务的三种方式】
【1】开启服务start-service
特点:服务在后台长期运行
(1) 定义一个类继承service
(2)第一次开启服务,服务会执行onCreate方法和onStart方法
(3)第二次开启服务,服务只会执行onStart方法
(4)服务一旦开启,服务就会在后台长期运行,在设置页面可以找到
【2】通过bindService绑定开启
特点:调用服务里面的方法
(1)在服务内部定义一个中间人对象(IBinder的实例)
(2)在onbind方法中把我们定义的中间人对象返回
(3)在Activity里面通过BindService 目的是获取中间人对象
(4)在获取中间人对象就可以间接的调用到服务里面的方法
MyCoon conn = new MyCoon();
bindService(intent,conn,BIND_AUTO_CREATE);
Service中的方法
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public class MyBinder extends Binder{
public void callBanZheng(int money){
//这里面就可以写绑定服务提供的方法
BanZheng(money);
}
}
中间人是我自己命名的,方便理解
private class MyCoon implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//获取中间人对象
myBinder = (DemoService.MyBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
【3】混合方式开启服务
需求:保证服务后台长期运行,并调用服务中的方法
(1)先开启startService保证服务在后台长期运行
(2)在使用bindService保证可以获取我们定义的中间的人对象,间接调用到服务里面的方法
(3)当activity销毁的时候 调用onBindservice解绑
Intent intent = new Intent(MainActivity.this, DemoService.class);
//先开始服务保障长期运行
startService(intent);
MyCoon conn = new MyCoon();
//再绑定
bindService(intent,conn,BIND_AUTO_CREATE);
解绑
@Override
protected void onDestroy() {
if (conn!=null){
unbindService(conn);
}
super.onDestroy();
}