Service的基本概念和用途:
Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果退出应用时,Service进程并没有结束,它仍然在后台运行,那什么时候会用到Service呢?比如播放音乐的时候,有可能想边听音乐边干些其他事情,当退出播放音乐的应用,如果不用Service,就听不到歌了,所以这时候就得用到Service了。又比如当一个应用的数据是通过网络获取的,不同时间的数据是不同的时候可以用Service在后台定时更新,而无须每打开应用的时候在去获取。
Service在Manifest.xml文件中像Activity一样,需要进行配置一下。
Service的生命周期:
Service分为:startService、bindService.
1、startService:
onCreate()
onStartCommand()
onStart()
onDestroy()
2、bindService:
onCreate()
onBind()
onServiceConnected()
onUnbind();
onDestroy()
四个功能【startService(), stopService(), bindService(), unbindService()】
流程:
- startService ---> stopService 生命周期, onCreate() --> onStartCommand() --> onStart() --> onDestroy();
- bindService ---> unbindService 生命周期, onCreate() --> onBind() --> onServiceConnected() --> onUnbind() --> onDestroy();
- startService ---> bindService --> stopService ---> unBindService 生命周期, onCreate() --> onStartCommand() --> onStart() -->onBind() -->onServiceConnected() --> onUnbind() --> onDestroy();
- startService --> bindService --> unBindService --> stopService 生命周期,onCreate() --> onStartCommand() --> onStart() --> onBind() --> onServiceConnected() --> onUnbind() --> onDestroy();
BindService并且与Activity进行交互:
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.e(KEY_TAG, "==================================onServiceConnected");
if(iBinder != null){
mBinderCreator = (ServiceCreator.BinderCreator)iBinder;
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.e(KEY_TAG, "==================================onServiceDisconnected");
}
};
前台Service:当内存不足时,不易被系统kill。
前台Service,相对与后台Service,优先级较高【当系统内存不足时,会优先Kill 后台
Service】