普通启动服务
普通服务的生命周期:
创建服务------->开启服务---------------->关闭服务
onCreate(); onStartCommand(); onDestroy():
onCreate()方法只会被执行一次。
服务类:
0. 注册服务类,在 清单文件中注册
1. 创建一个类 ,该类继承Service抽象类,并重写其中的抽象方法
public class MyService extends Service {
自动重写:
public IBinder onBind(Intent intent) {
2. 重写 服务创建时调用的方法
public void onCreate() {
3. 重写 开启服务时调用的方法
已过时:
public void onStart(Intent intent, int startId) {
更新为:
public int onStartCommand(Intent intent, int flags, int startId) {
4. 重写 停止服务时调用的方法,将该服务进行销毁
public void onDestroy() {
Activity类:
在Activity中开启服务:
Intent service = new Intent(this, MyService.class);
startService(service);
停止服务:
stopService(service);
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
如何通过 普通服务调用 服务中的音乐方法:
方法重点:
通过Intent传值, 对标记进行判断,从而调用不同的方法
1. 开启服务后
2. 根据不同的 需求,传入 对应的状态值
service.putExtra("music",1);
startService(service);
3. 在服务中,在 服务开启调用方法中,对传入的不同状态值进行判断(根据开启方法中的 intent参数进行状态值获取)
public int onStartCommand(Intent intent, int flags, int startId) {
int i=intent.getIntExtra("music",默认值);
switch(i){
4. 根据不同的状态值,调用不同的功能方法
普通服务的生命周期:
创建服务------->开启服务---------------->关闭服务
onCreate(); onStartCommand(); onDestroy():
onCreate()方法只会被执行一次。
服务类:
0. 注册服务类,在 清单文件中注册
1. 创建一个类 ,该类继承Service抽象类,并重写其中的抽象方法
public class MyService extends Service {
自动重写:
public IBinder onBind(Intent intent) {
2. 重写 服务创建时调用的方法
public void onCreate() {
3. 重写 开启服务时调用的方法
已过时:
public void onStart(Intent intent, int startId) {
更新为:
public int onStartCommand(Intent intent, int flags, int startId) {
4. 重写 停止服务时调用的方法,将该服务进行销毁
public void onDestroy() {
Activity类:
在Activity中开启服务:
Intent service = new Intent(this, MyService.class);
startService(service);
停止服务:
stopService(service);
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
如何通过 普通服务调用 服务中的音乐方法:
方法重点:
通过Intent传值, 对标记进行判断,从而调用不同的方法
1. 开启服务后
2. 根据不同的 需求,传入 对应的状态值
service.putExtra("music",1);
startService(service);
3. 在服务中,在 服务开启调用方法中,对传入的不同状态值进行判断(根据开启方法中的 intent参数进行状态值获取)
public int onStartCommand(Intent intent, int flags, int startId) {
int i=intent.getIntExtra("music",默认值);
switch(i){
4. 根据不同的状态值,调用不同的功能方法