本篇的内容并不是介绍service使用方法和生命周期的,而是对其中的一些要点进行记录和分析。 我们都知道,Service是一个在后台执行的应用组件,用于在后台进行长期操作,例如进行网络事务,播放背景音乐等等。它又两种启动方式,如果其他的应 ...
本篇的内容并不是介绍service使用方法和生命周期的,而是对其中的一些要点进行记录和分析。
我们都知道,Service是一个在后台执行的应用组件,用于在后台进行长期操作,例如进行网络事务,播放背景音乐等等。它又两种启动方式,如果其他的应用组件希望与该service进程内通信(IPC),可以通过与该service绑定来实现。关于生命周期的问题就不啰嗦了,直接放官档的图:
无论何种方式启动service,任何应用组件都可以使用该service。如果希望只有你自己的app才能使用该service,那么需要在manifest文件中加入android:exported
属性,并将其设置为false。Android官方建议我们尽量使用显式的方式来启动service,从而保证app的安全。
另外,我们需要注意的是,在默认情况下service并不会重新开启一个独立的线程运行,而是运行于宿主进程的主线程中。显然,如果我们需要进行耗时操作,例如上面提到的播放背景音乐,网络操作等等,该如何解决?
- 我们可以在activity中创建新线程,并在activity中对线程进行创建启动和销毁;
- 使用asyncTask来完成任务;
- 在service中新开一个线程来完成这些任务,以防ANR错误。
IntentService
当我们不需要同时处理多个请求的情况下,我们最好的解决方案是使用IntentService完成任务,而我们只需重写onHandleIntent()来完成处理逻辑即可。在IntentService进行了以下工作:
- 新启动了一个worker线程来执行那些提交给onStartComand方法的intent任务。
- 创建了一个work队列来存放多个请求任务,每次只向onHandleIntent()方法来传递一个intent来处理。
- 当所有请求任务都完成后,则自动停止该service。
- 默认的onStartCommand()方法中,将收到的intent参数传递给onHandleIntent()来处理。
下面是一个IntentService的示例:
public class HelloIntentService extends IntentService { /** * A constructor is required, and must call the super IntentService(String) * constructor with a name for the worker thread. */ public HelloIntentService() { super("HelloIntentService"); } /** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. */ @Override protected void onHandleIntent(Intent intent) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. long endTime = System.currentTimeMillis() + 5*1000; while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (Exception e) { } } } }}
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:Service不完全解析
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。