Android之Service与IntentService的比较
? ? ? ?不知道大家有沒有和我一樣,以前做項目或者練習的時候一直都是用Service來處理后臺耗時操作,卻很少注意到還有個IntentService,前段時間準備面試的時候看到了一篇關于IntentService的解釋,發現了它相對于Service來說有很多更加方便之處,今天在這里稍微來總結下我的心得。
? ? 首先IntentService是繼承自Service的,那我們先看看Service的官方介紹,這里列出兩點比較重要的地方:
? ? ??1.A Service is?not?a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
? ? ? 2.A Service is?not?a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
? ? ? 稍微翻一下(英文水平一般)
? ? ? 1.Service不是一個單獨的進程 ,它和應用程序在同一個進程中。
? ? ? 2.Service不是一個線程,所以我們應該避免在Service里面進行耗時的操作
關于第二點我想說下,不知道很多網上的文章都把耗時的操作直接放在Service的onStart方法中,而且沒有強調這樣會出現Application Not Responding!希望我的文章能幫大家認清這個誤區(Service不是一個線程,不能直接處理耗時的操作)。
? ? ? ?有人肯定會問,那么為什么我不直接用Thread而要用Service呢?關于這個,大家可以網上搜搜,這里不過多解釋。有一點需要強調,如果有耗時操作在Service里,就必須開啟一個單獨的線程來處理!!!這點一定要銘記在心。??
? ? ? ?IntentService相對于Service來說,有幾個非常有用的優點,首先我們看看官方文檔的說明:
? ? ? ? ?IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests throughstartService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
? ? ? ? ?This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
? ? ? ? ?All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
? ? ? ?1.Service:
[java]?view plaincopyprint?
[java]?view plaincopyprint?
測試主程序:
[java]?view plaincopyprint?轉載于:https://www.cnblogs.com/wuwuwu/p/6162706.html
總結
以上是生活随笔為你收集整理的Android之Service与IntentService的比较的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ajax请求session超时处理流程(
- 下一篇: 本案例通过ArrayList集合来显示C