展会信息港展会大全

什么是service service的启动方法 生命周期
来源:互联网   发布日期:2016-01-13 22:20:34   浏览:4030次  

导读:一,什么是service1, 不可见,后台运行,2,耗时时间长。3,是一个应用程序组件4,没有图形化界面5.可以使用service来更新ContentProvider ,发送intent 以及启动系统的通知等等。二,service不是什么,1,他......

一,什么是service

1, 不可见,后台运行,

2,耗时时间长。

3,是一个应用程序组件

4,没有图形化界面

5.可以使用service来更新ContentProvider ,发送intent 以及启动系统的通知等等。

二,service不是什么,

1,他不是一个单独的进程(拥有独立的系统资源,可以有多个线程,一个应用程序必须自己的进程)

2,他不是一个单独的线程(线程之间使用时间片轮来调度,一个线程使用的是它所在进程的资源)

三,service的启动方法

在别的intent中启动,Intent intent = new Intent();

intent.setClass(TestActivity.this, FirstService.class);

startService(intent);

StopService :

Intent intent = new Intent();

intent.setClass(TestActivity.this, FirstService.class);

stopService(intent);

1,context.startService()

使用使用context.bindService()启动Service会经历:

context.bindService()->onCreate()->onBind()->Service running

onUnbind() -> onDestroy() ->Service stop

如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。

stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service。

所以调用startService的生命周期为:onCreate --> onStart(可多次调用) --> onDestroy

2, context.bindService()。

使用使用context.bindService()启动Service会经历:

context.bindService()->onCreate()->onBind()->Service running

onUnbind() -> onDestroy() ->Service stop

onBind 将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者 (Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用 onUnbind->onDestroy相应退出。

所以调用bindService的生命周期为:onCreate --> onBind(只一次,不可多次绑定) --> onUnbind --> onDestory。 注意:在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。

3,注册service 在manifest中:<service android:name=".FirstService"></service>

4,public int onStartCommand(Intent intent, int flags, int startId),onStartCommand 这里的intent是指service class,

Android 开发的过程中,每次调用startService(Intent)的时候,都会调用该Service对象的 onStartCommand(Intent,int,int)方法,然后在onStartCommand方法中做一些处理。然后我们注意到这个函数有一 个int的返回值,这篇文章就是简单地讲讲int返回值的作用。

从Android官方文档中,我们知道onStartCommand有4种返回值:

START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试 重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在 此期间没有任何启动命令被传递到service,那么参数Intent将为null。

START_NOT_STICKY: 非粘性的 。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。

START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。

START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。

赞助本站

人工智能实验室
AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港