1、作用:
执行不需要和用户交互而且需要长期运行的任务。(关键词:后台、长期运行)
2、注意点:
(1)Service默认运行在UI线程;(2)Service运行不依赖任何用户界面,任何界面的切换或者打开另一个应用程序均对它没有影响;
(3)Service关闭时,若在Service中开启的子线程未结束,则关闭Service也不会结束其子线程;
(4)前台服务即使在应用程序退出杀掉了,服务也会依然存在。(这个不确定,有的手机杀掉应用程序后前台服务也会退出)
3、生命周期回调方法:
onCreate() - onStartCommand() - onDestory()4、启动方式:
(1)startService
1、首次创建Service会回调onCreate()方法,再次startService时,只会执行onStartCommand();
2、关闭服务:stopService或者在Service中stopSelf(),这时会回调onDestory();
(2)bindService (也称为可交互的后台服务)
1、生命周期:onCreate() - onBind() - 会调用Activity中的ServiceConnection接口的onServiceConnected()方法- onUnBind() -onDestory()
(3)同时使用startService和bindService
生命周期:onCreate() - onStartCommand() - onBind() - onUnBind() - onDestory()
1、首次创建Service会回调onCreate()方法,再次startService时,只会执行onStartCommand();
2、关闭服务:stopService或者在Service中stopSelf(),这时会回调onDestory();
(2)bindService (也称为可交互的后台服务)
1、生命周期:onCreate() - onBind() - 会调用Activity中的ServiceConnection接口的onServiceConnected()方法- onUnBind() -onDestory()
(3)同时使用startService和bindService
生命周期:onCreate() - onStartCommand() - onBind() - onUnBind() - onDestory()
5、前台服务
1、作用:避免服务在内存较低的情况下被系统回收杀死2、创建方法:在onCreate()中创建一个Notification,然后使用Service的startForeground(flag,Notification)方法
6、IntentService
1、作用:专门用来解决Service中不能执行耗时操作这一问题2、创建方法:继承IntentService并且覆写onHandlerIntent()方法,在onHandlerIntent方法中执行耗时操作
7、AIDL
待补充
8、AccessibilityService无障碍服务
待补充
9、系统服务
(1)作用:查询机器当前各种信息
(2)举例:getSystemService(serviceName);