Android-Service

本文详细介绍了 Android 中 Service 的工作原理,包括其运行线程特性、startService 和 bindService 的交互方式以及如何避免 ANR 错误等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、问题列表

1.1、service是运行在一个单独的线程?

官方原文:
Caution:  A service runs in the main thread of its hosting process—the service does  not  create its own thread and does  not  run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

并不是运行在一个单独的线程的,是运行在启动他的组件的主线程上的。所以如果我们需要在service中做一些耗时的操作,需要自己另外启一个线程。

1.2、service可以同时被startService()和bindService()启动吗?

官方原文: These two paths are not entirely separate. That is, you can bind to a service that was already started with startService() . For example, a background music service could be started by calling  startService()  with an Intent  that identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling  bindService() . In cases like this,  stopService()  or  stopSelf()  does not actually stop the service until all clients unbind.

一个service可以同时被startService()和bindService()

1.2、service的声明周期



2、demo

2.1、范德萨


3、相关链接

3.1、官方

Guide(Service):http://developer.android.com/guide/components/services.html#Notifications
Guide(BoundService):http://developer.android.com/guide/components/bound-services.html

3.2、网友


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值