每天一个安卓知识

安卓开发之Service(服务)
Service 是安卓四大组件之一,用于在后台执行长时间运行的任务(如下载、播放音乐等),不提供用户界面。即使应用切换到后台或用户打开其他应用,Service 仍可继续工作。
一、Service 的基本特点
– 后台运行:无需用户交互,适合耗时操作(如下载文件)。
– 生命周期管理:通过 startService() 或 bindService() 启动,需手动管理生命周期(避免内存泄漏(https://open.toutiao.com/article/url/?param=6hc8hs6W7EB2teQ9CY2wktHxAyTiTpGLnrgxM66hZpM9vN4fSfh3b9JK7iWzf55Ef6LPqEnfQkuhJdZedKWCtnSJP8zuLBhVBUbnBpJ2mkPDLSafUdiVh7vB33S16xVZgBXrLjRpeCWfPyAQ3LDs1GEwWPhGgJagTrMprEjhf9PNZZX6C7BTWbYzz971Kq2z6pNt63ErLvzuy2MbMPF9QzYAWAD4CXvDi4BEwFV1nTeFAX9&partner=agent_bot_7520145467502544393_default_content&version=3))。
– 低优先级:系统内存不足时可能被回收,可通过 startForegroundService() 提升优先级(需显示通知)。
二、Service 的两种启动方式
1. startService():独立运行
– 特点:启动后与启动组件(如 Activity)无关,需调用 stopSelf() 或 stopService() 停止。
– 生命周期: onCreate() → onStartCommand() → onDestroy()
– 示例:播放音乐(即使退出 Activity,音乐仍继续播放)。
// 启动 Service
Intent intent = new Intent(this, MyService.class);
startService(intent);
// 停止 Service(在 Service 内部)
stopSelf();
2. bindService():绑定组件
– 特点:与启动组件(如 Activity)绑定,组件销毁时 Service 也会停止,支持组件间通信(通过 Binder)。
– 生命周期: onCreate() → onBind() → onUnbind() → onDestroy()
– 示例:应用内实时数据更新(如天气 app 后台获取数据并更新 UI)。
// 绑定 Service(需实现 ServiceConnection 接口)
Intent intent = new Intent(this, MyService.class);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
#安卓开发 #安卓入门教程
Service 是安卓四大组件之一,用于在后台执行长时间运行的任务(如下载、播放音乐等),不提供用户界面。即使应用切换到后台或用户打开其他应用,Service 仍可继续工作。
一、Service 的基本特点
– 后台运行:无需用户交互,适合耗时操作(如下载文件)。
– 生命周期管理:通过 startService() 或 bindService() 启动,需手动管理生命周期(避免内存泄漏(https://open.toutiao.com/article/url/?param=6hc8hs6W7EB2teQ9CY2wktHxAyTiTpGLnrgxM66hZpM9vN4fSfh3b9JK7iWzf55Ef6LPqEnfQkuhJdZedKWCtnSJP8zuLBhVBUbnBpJ2mkPDLSafUdiVh7vB33S16xVZgBXrLjRpeCWfPyAQ3LDs1GEwWPhGgJagTrMprEjhf9PNZZX6C7BTWbYzz971Kq2z6pNt63ErLvzuy2MbMPF9QzYAWAD4CXvDi4BEwFV1nTeFAX9&partner=agent_bot_7520145467502544393_default_content&version=3))。
– 低优先级:系统内存不足时可能被回收,可通过 startForegroundService() 提升优先级(需显示通知)。
二、Service 的两种启动方式
1. startService():独立运行
– 特点:启动后与启动组件(如 Activity)无关,需调用 stopSelf() 或 stopService() 停止。
– 生命周期: onCreate() → onStartCommand() → onDestroy()
– 示例:播放音乐(即使退出 Activity,音乐仍继续播放)。
// 启动 Service
Intent intent = new Intent(this, MyService.class);
startService(intent);
// 停止 Service(在 Service 内部)
stopSelf();
2. bindService():绑定组件
– 特点:与启动组件(如 Activity)绑定,组件销毁时 Service 也会停止,支持组件间通信(通过 Binder)。
– 生命周期: onCreate() → onBind() → onUnbind() → onDestroy()
– 示例:应用内实时数据更新(如天气 app 后台获取数据并更新 UI)。
// 绑定 Service(需实现 ServiceConnection 接口)
Intent intent = new Intent(this, MyService.class);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
#安卓开发 #安卓入门教程
夜雨聆风
