Service
能够在后台长时间运行,并且没有用户界面的应用程序组件。
Service按启动方式可以分为Started Service和Bound Service。
Started Service:调用startService()方法来启动的Service,通过这个方法运行应用的时候服务并没有启动,当应用程序组件调用这个startService()方法时才启动。
Bound Service:调用bindService()方法来启动,当应用运行的时候这个Service和Activity就绑定到一起了,当Activity停止,Service也会相应停止。
Service的基本用法:
在Android Studio中可以直接新建一个Service,在这个类中,重写onBind()、onCreate()、onStartCommand()、onDestroy()方法。onCreate()方法在创建时应用,onStartCommand()方法在每次启动Service时调用,onDestroy()在Service销毁的时候调用。
在创建了这个Service后Android Studio会自动在AndroidManifest.xml中配置这个Service通过Service标签,其中enabled属性是指这个Service能否被实例化,exported属性是指其他应用程序是否可以调用这个Service或与之交互。
//启动Service首先需要一个Intent对象,并实例化这个Intent对象
Intent intent =