Android Service的使用

Service作为Android四大组件之一,应用非常广泛。 
 和activity一样,service也有一系列的生命周期回调函数,你可以实现它们来监测service状态的变化,并且在适当的时候执行适当的工作。

服务一般分为两种:

1:本地服务, Local Service 用于应用程序内部。在Service可以调用Context.startService()启动,调用Context.stopService()结束。 在内部可以调用Service.stopSelf() 或 Service.stopSelfResult()来自己停止。无论调用了多少次startService(),都只需调用一次 stopService()来停止。

2:远程服务, Remote Service 用于android系统内部的应用程序之间。可以定义接口并把接口暴露出来,以便其他应用进行操作。客户端建立到服务对象的连接,并通过那个连接来调用服 务。调用Context.bindService()方法建立连接,并启动,以调用 Context.unbindService()关闭连接。多个客户端可以绑定至同一个服务。如果服务此时还没有加载,bindService()会先加 载它。 
提供给可被其他应用复用,比如定义一个天气预报服务,提供与其他应用调用即可。

Android Service的生命周期

说到service生命周期,我们来建个类继承一下service看看

这里写图片描述

周期图:

这里写图片描述

public class DemoService extends Service {


    @Override
    public void onCreate() {
        super.onCreate();
        // The service is being created
        创建服务
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
        // The service is starting, due to a call to startService()
        开始服务
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
        绑定服务
        // A client is binding to the service with bindService()
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
        // All clients have unbound with unbindService()
        解绑服务
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        销毁服务
        // The service is no longer used and is being destroyed
    }
 }

如何启动服务,外部方法有哪些?

startService(),启动服务 
stopService(),停止服务 
bindService(),绑定服务 
unbindService(),解绑服务

生命周期方法简单介绍

startService()

作用:启动Service服务 
手动调用startService()后,自动调用内部方法:onCreate()、onStartCommand() 
如果一个service被startService多次启动,onCreate()只会调用一次 
onStartCommand()调用次数=startService()次数

stopService()

作用:关闭Service服务 
手动调用stopService()后,自动调用内部方法:onDestory() 
如果一个service被启动且被绑定,如果没有在绑定的前提下stopService()是无法停止服务的。

bindService()

作用:绑定Service服务 
手动调用bindService()后,自动调用内部方法:onCreate()、onBind()

unbindService()

作用:解绑Service服务 
手动调用unbindService()后,自动调用内部方法:onCreate()、onBind()、onDestory()

注意

startService()和stopService()只能开启和关闭Service,无法操作Service; 
bindService()和unbindService()可以操作Service

startService开启的Service,调用者退出后Service仍然存在; 
BindService开启的Service,调用者退出后,Service随着调用者销毁。

以上是对服务的简单讲述,接下来会讲解更多。

猜你喜欢

转载自blog.csdn.net/dpl12/article/details/82726105