【Android初级工程师】Service

概要说明

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

Service执行长时间运行在后台的操作而没有提供可以和用户交互的页面,其他应用可以启动本应用的服务即使切换到了其他应用上。Service可以通过绑定的方式来完成进程间的通信,它很类似于Activity,但是却是没有前台页面的Activity。

启动模式

Service的定义方式有两种,根据特点和需要选择一种来使用service,当然如果需要,可以两种同时使用。

Started:
通过调用startService()方法开启一个service,这种方式一旦启动了service,它的生命周期与启动它的组件没有关系,即使启动它的组件已经销毁,它也仍然存活。这种方式通常执行一些简单的工作并且不需要返回结果给启动者,例如下载文件,当文件下载完成之后,service需要stop自己即可。
Intent intent = new Intent(this, HelloService.class);
startService(intent);
Bound
通过组件调用bindService()将service和自己绑定起来,显然绑定之后的service和绑定者共有生命周期,并且会返还一个IBind参数来进行数据交互。多个组件可以同时绑定一个service,但是只有所有的组件都解除绑定之后,service才会销毁。
Intent intent = new Intent(this, HelloService.class);
bindService(intent, conn, Context.BIND_AUTO_CREATE);
startService(intent);

需要注意的是,service不会主动开启新的线程去完成任务,如果你需要进行一些耗时的操作,最好新建一条线程去启动service,或者使用Service的子类IntentService,它内部实现了新的线程。

注册方式

Service和Activity一样需要在AndroidManifest.xml文件中注册

<manifest ... >
  ...
  <application ... >
      <service android:name=".ExampleService" />
      ...
  </application>
</manifest>

生命周期

这里写图片描述

Service的生命周期相对较简单:
entire lifetime:从onCreate()到onDestroy()方法就是整个生命周期,不管是started方式还是bind方式。
active lifetime:onStartCommand()或者onBind()方法开始,如果是started方式则在onDestroy()时结束,如果是bind方式则在onUnbind()调用时结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值