目录
应用场景
不需要和用户交互还要长期运行的任务(处理网络事务、播放音乐、文件I/O)。service可由其他应用组件启动,即使用户切换到其他应用,service仍在后台继续运行。此外,组件可以通过绑定到服务与之进行交互,甚至执行进程间通信(IPC)。
生命周期
onCreate:服务创建时调用
onStartCommand:服务启动时调用
onDestory:服务销毁时调用
常用API
stopSelf:服务端自己调用停止服务
onBind:其他组件调用bindservice被触发
启动服务
Intent intent_start_service = new Intent(FirstActivity.this, MyService.class);
startService(intent_start_service);
//第一次startService会调用service的onCreate->onStartCommand,之后再调用startService都只会调用onStartCommand,每个service只会存在一个实例
停止服务
activity停止service的方式
Intent intent_stop_service = new Intent(FirstActivity.this, MyService.class);
stopService(intent_start_service);//会调用service的onDestory
service自己停止的方式
stopSelf,也会调用service的onDestory
服务类型
前台服务
前台服务执行一些用户能注意到的操作。例如,音频应用会使用前台服务来播放音频曲目。前台服务必须显示通知。
google前台服务:https://developer.android.google.cn/guide/components/foreground-services
前台服务创建
1.需要在manifest.xml文件中声明
2.通过startForegroundService创建
后台服务
后台服务执行用户注意不到的操作。
注意,后台服务优先级低,在内存紧张时容易被kill,使用前台进程可以提高优先级。
服务保活
参考:https://blog.csdn.net/tantion/article/details/88714287
绑定
google绑定服务:https://developer.android.google.cn/guide/components/bound-services
activity和service绑定
作用
绑定后,实现activity和service的通信通道。这样activity可以根据service的信息来更新UI。在activity中可以操作service(activity可以调用service的API)
API
bindService:能够在activity中获取service实例,进而实现activity和service的交互、发送请求、接收结果
unbindService:解绑
绑定demo
-
activity端调用bindService,bindService需要serviceConnection作为参数,所以先创建ServiceConnection对象
-
bindService会触发service端的onBind接口,onBind会返回IBinder对象作为onServiceConnected中的service参数
-
activity可通过CommunicateBinder.getService拿到service实例,这样就可以调用service的API
-
通过bind,建立了service和activity的通道,service可向activity发送message
-
如果bindService调用时,service还未创建,会执行servcie的onCreate,但不会执行onStartCommand
-
如果servcie执行了startService,又执行了bindService,此时stopService是不会触发onDestory,必须unbindService和stopService都调用才会onDestory。
参考
https://developer.android.google.cn/guide/components/services