Android四大组件Service

2020-02-28  本文已影响0人  星邪Ara

文章脑图

文章内容

1、Service 启动过程

2、什么是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两种启动方式

7、Service显式和隐式

显式启动

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

隐式启动

<-- 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);  
// 方式一
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面试题

上一篇下一篇

猜你喜欢

热点阅读