美文网首页
Android四大组件Service

Android四大组件Service

作者: 星邪Ara | 来源:发表于2020-02-28 09:00 被阅读0次

    文章脑图

    文章内容

    1、Service 启动过程

    2、什么是Service

    • Service服务是Android四大组件之一,是一种程序后台运行的方案,用于执行长时间运行且不需要用户交互的任务。
    • Service并不是在单独进程中运行,而是运行在应用程序的主线程中,在执行具体耗时任务过程中要手动开启子线程,应用程序进程被杀死,所有依赖该进程的服务也会停止运行。

    3、Service分类

    Service本地、可通信的、前台、远程使用

    远程服务Service,AIDL & IPC讲解

    4、Service两种状态

    启动状态(Started):

    Android的应用程序组件,如Activity,通过startService()启动了服务,则服务是Started状态。一旦启动,服务可以在后台无限期运行,即使启动它的组件已经被销,除非手动调用才能停止服务, 已启动的服务通常是执行单一操作,而且不会将结果返回给调用方。

    绑定状态(Bound):

    当Android的应用程序组件通过bindService()绑定了服务,则服务是Bound状态。Bound状态的服务提供了一个客户服务器接口来允许组件与服务进行交互,如发送请求,获取结果,甚至通过IPC来进行跨进程通信。仅当与另一个应用组件绑定时,绑定服务才会运行。 多个组件可以同时绑定到该服务,但全部取消绑定后,该服务即会被销毁。

    5、Service生命周期

    Service生命周期

    onCreate()

    首次创建服务时,系统将调用此方法。如果服务已在运行,则不会调用此方法,该方法只调用一次。

    onStartCommand()

    当另一个组件通过调用startService()请求启动服务时,系统将调用此方法。

    onDestroy()

    当服务不再使用且将被销毁时,系统将调用此方法。

    onBind()

    当另一个组件通过调用bindService()与服务绑定时,系统将调用此方法。

    onUnbind()

    当另一个组件通过调用unbindService()与服务解绑时,系统将调用此方法。

    onRebind()

    当旧的组件与服务解绑后,另一个新的组件与服务绑定,onUnbind()返回true时,系统将调用此方法。

    参考

    Service生命周期浅析

    6、Service两种启动方式

    • startService 启动的服务:主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopService。同一个Service Start多次,onCreate()执行一次,onStartCommand()执行多次。

    • bindService 启动的服务:该方法启动的服务可以进行通信。停止服务使用unbindService。同一个Service bind多次, onCreate()执行一次,onBind()也执行一次。

    7、Service显式和隐式

    显式启动

    Intent intent = new Intent(this, Service.class);  
    startService(intent);  
    

    隐式启动

    • Android5.0之前
    <-- AndroidManifest.xml清单配置 -->
    <service android:name=".service">  
        <intent-filer>  
            <action android:name="com.android.service"/>  
        <intent-filer>  
    </service>  
    
    //代码
    Intent intent = new Intent("com.android.service");  
    startService(intent);  
    
    • Android5.0之后
    // 方式一
    Intent intent = new Intent();
    //serviceName="com.ara.test",serviceName 必须是完整的类名
    ComponentName componentName = new ComponentName(pkgName, serviceName);
    intent.setComponent(componentName);
    context.startService(intent);
    
    // 方式二
    Intent intent = new Intent();
    intent.setAction("com.android.service");//Service能够匹配的Action
    intent.setPackage("com.ara.test");//应用的包名
    context.startService(intent);
    

    8、IntentService源码分析

    9、Service面试题

    相关文章

      网友评论

          本文标题:Android四大组件Service

          本文链接:https://www.haomeiwen.com/subject/makkhhtx.html