Service介绍
1.Service,服务,四大组件之一,和Activity相似,一般运行在后台,没有用户界面可执行的程序
2.Activity和Service区别:
(1)不同点:
Activity:可以和用户交互,页面可见
Service:后台运行,没有界面
(2)相同点:
在清单文件中注册,都有自己的生命周期
Service特点
service在后台运行,不能与用户交互,即使应用退出,服务也不会停止,当应用进程被杀死,服务停止
service运行在主线程中,当需要执行耗时操作时,需要在服务中创建子线程完成
service用途:播放音乐、后台下载等
Service启动方式及生命周期
启动方式一(startService)
右键创建一个Service
public class MyService extends Service {
public MyService() {
Log.i("aaa","Service被创建");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
java代码
Intent intent = new Intent(this, MyService.class);
startService(intent);
关闭服务:
stopService(intent);
如果服务已经开启,不会重复执行onCreate(),而是调用onStart()或onStartCommand(),停止服务的时候调用onDestroy()
启动方式:onCreate() — onStartCommand() — onDestroy()
开启服务:startService()
停止服务:stopService()
启动方式二(bindService)
创建服务:自定义类继承Service,返回代理人,方便开启者调用服务中的方法
public class MyService