1.Service定义:
首先,Service作为Android四大组件之一,其主要特点就是:可以长时间运行在后台进行操作并且无UI页面的Android组件。
2.Service生命周期:
public class MyService extends Service { @Override public void onCreate() { super.onCreate();
//Service创建 }
@Override public IBinder onBind(Intent intent) {
//Service被绑定 (当使用 bindService()启动Service的时候会调用此方法) return null; } @Override @Deprecated public void onStart(Intent intent, int startId) { super.onStart(intent, startId);
// (当使用 startService()启动Service的时候会调用此方法) } @Override public int onStartCommand(Intent intent, int flags, int startId) {
// (当使用 startService()启动Service的时候会调用此方法) return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() {
super.onDestroy();
//service销毁 } }
3.Service的使用方式
(1)startService(Intent serviceIntent)
此种方式启动Service有几个主要的特点:
1.Service不与启动它的组件绑定,当启动它的组件被销毁时,Service仍然会运行
2.没有提供默认的与组件的通信方式,可以理解为使用此方式启动的Service处于独立运行状态
3.需要停止Service,可以在其他组件中调用stopService(),或在Service中调用stopSelf()
(2)bindService(Intent serviceIntent,,ServiceConnection connection ,int flags)
首先介绍一下此方法使用的三个参数:
参数1:为制定Service类的Intent对象不做过多解释
参数2:ServiceConnection 对象,主要用于与组件进行通信,具体使用后续会介绍
参数3:flags,它是一个标识绑定选项的值,通常使用BIND_AUTO_CREATE就可以
此种方式启动Service有几个主要的特点:
1.当它绑定的组件被销毁时,该服务也会被销毁
2.提供了通信方式用于跟组件通信,主要使用ServiceConnection 来完成,后续会详细介绍
3.需要停止Service,可以在其他组件中调用unBindService(),或在Service中调用stopSelf()