1. 程式人生 > >Android之Service與IntentService的比較

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.
e使用佇列的方式將請求的Intent加入佇列,然後開啟一個worker thread(執行緒)來處理佇列中的Intent,對於非同步的startService請求,IntentService會處理完成一個之後再處理第二個,每一個請求都會在一個單獨的worker thread中處理,不會阻塞應用程式的主執行緒,這裡就給我們提供了一個思路,如果有耗時的操作與其在Service裡面開啟新執行緒還不如使用IntentService來處理耗時操作。下面給一個小例子:

1.Service:



    package com.zhf.service;  

    import Android.app.Service;  
    import Android.content.Intent;  
    import Android.os.IBinder;  

    public class MyService extends Service {  

        @Override  
        public void onCreate() {  
            super.onCreate();  
        }  

        @Override  
        public void onStart(Intent intent, int startId) {  
            super.onStart(intent, startId);  
            //經測試,Service裡面是不能進行耗時的操作的,必須要手動開啟一個工作執行緒來處理耗時操作   
            System.out.println("onStart");  
            try {  
                Thread.sleep(20000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            System.out.println("睡眠結束");  
        }  

        @Override  
        public IBinder onBind(Intent intent) {  
            return null;  
        }  
    }  

2.IntentService:



    package com.zhf.service;  

    import Android.app.IntentService;  
    import Android.content.Intent;  

    public class MyIntentService extends IntentService {  

        public MyIntentService() {  
            super("yyyyyyyyyyy");  
        }  

        @Override  
        protected void onHandleIntent(Intent intent) {  
            // 經測試,IntentService裡面是可以進行耗時的操作的   
            //IntentService使用佇列的方式將請求的Intent加入佇列,然後開啟一個worker thread(執行緒)來處理佇列中的Intent   
            //對於非同步的startService請求,IntentService會處理完成一個之後再處理第二個   
            System.out.println("onStart");  
            try {  
                Thread.sleep(20000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            System.out.println("睡眠結束");  
        }  
    }  

測試主程式:



    package com.zhf.service;  

    import Android.app.Activity;  
    import Android.content.Intent;  
    import Android.os.Bundle;  

    public class ServiceDemoActivity extends Activity {  
        /** Called when the activity is first created. */  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.main);  
            startService(new Intent(this,MyService.class));//主介面阻塞,最終會出現Application not responding   
            //連續兩次啟動IntentService,會發現應用程式不會阻塞,而且最重的是第二次的請求會再第一個請求結束之後執行(這個證實了IntentService採用單獨的執行緒每次只從佇列中拿出一個請求進行處理)   
            startService(new Intent(this,MyIntentService.class));  
            startService(new Intent(this,MyIntentService.class));  
        }  
    }

相關推薦

AndroidServiceIntentService比較

不知道大家有沒有和我一樣,以前做專案或者練習的時候一直都是用Service來處理後臺耗時操作,卻很少注意到還有個IntentService,前段時間準備面試的時候看到了一篇關於IntentService的解釋,發現了它相對於Service來說有很多更加方便之處,今天在這裡稍微來總結下我的心得。首先Intent

Android開發ServiceIntentService的區別使用場景

Service Service 是長期執行在後臺的應用程式元件。 Service 不是一個單獨的程序,它和應用程式在同一個程序中,Service 也不是一個執行緒,它和執行緒沒有任何關係,所以它不能直接處理耗時操作。如果直接把耗時操作放在 Service 的 onStartCommand() 中,

AndroidServiceIntentService的差別

前言: ServiceTimeout(20 seconds)小概率型別Service在特定的時間內無法處理完成,會造成ANR — 應用程式無響應(ANR:Application Not Responding)的情況 ▲ 分析 : 避免ANR最核心的一點就是在主執行緒減少耗時操作。這時我們

多執行緒Locksynchronized比較及使用

   第一:先比較兩者的區別: 類別 synchronized

AndroidwebViewjs互動

一、java呼叫js操作: 1.佈局檔案: <WebView android:id="@+id/web" android:layout_width="match_parent" android:layout_height="mat

解讀AndroidService(1)基礎知識

本文翻譯自Android官方文件 一個Service是一個長期可以在後臺執行(當然不需要提供UI)的應用元件。其它元件可以啟動service,即使切換到另一個應用,該service仍然可以在後臺執行。另外,其它元件可以繫結一個service進行互動,甚至可以進行程序間通訊(interproces

Web Servicerestful比較

一、web Service     1、WebService是什麼      web service是一種跨程式語言和跨作業系統平臺的遠端呼叫技術, 所謂跨程式語言和跨操作平臺,就是說服務端程式採用java編寫,客戶端程式

Android重寫過載

1、過載與重寫的區別 方法過載是指同一個類中的多個方法具有相同的名字,但這些方法具有不同的引數列表(引數的數量或者引數型別不能完全一樣) 方法重寫發生在子父類之間的,子類定義的方法與父類中的方法具有相同的方法名字,相同的引數列表和相同的返回型別 2.過載(Overloading) 理

AndroidService

1.Service的基本認識 1.1 Service是什麼?   Service(服務)是一個一種可以在後臺執行長時間執行操作而沒有使用者介面的元件。它運行於UI執行緒,因此不能進行耗時的操作。 1.2 Service和Thread的區別   Service的

Android“註解反射”

原文連結:理解Android中的註解與反射 反射 Java反射(Reflection)定義 Java反射機制是指在執行狀態中 對於任意一個類,都能知道這個類的所有屬性和方法; 對於任何一個物件,都能夠呼叫它的任何一個方法和屬性; 這樣動態獲取新的以及動態呼叫物件方法

Xamarin.AndroidActionBar選單

1 [Activity(Label = "ActionBarStudy", MainLauncher = true, Icon = "@drawable/icon")] 2 public class MainActivity : Activity 3 { 4

AndroidWebViewURLConnection

demo java程式碼: public class MainActivity extends Activity implements View.OnClickListener { private TextView mTextViewDetail

AndroidService自啟動流程

 當Service被異常銷燬後,預設都會自動重啟,但Service的自動重啟是如何實現的尼?下面就來梳理一下Service的自動重啟流程。  無論Service是啟動還是繫結成功,都會呼叫ActiveServices的serviceDoneExecutingLocked方法,來看一下這個

AndroidService使用詳解

 本篇文章主要是講解一些關於Service的知識點。 Service的生命週期  Service有兩種啟動方式,startService與bindService。  首先來看startService,通過該方式啟動的Service與呼叫者沒有任何關聯,呼叫者也無法呼叫該Servi

AndroidService學習篇一:Service啟動方式startService

Service概念及用途: A service is an application component that can perform long-running operations in the background and does not provide a u

AndroidServiceActivity資料互動的簡單理解

Service跟Activity是最相似的元件,都代表可執行的程式,區別在於:Service一直在後臺執行,沒有跟使用者互動的介面。 啟動與停止Service有兩種方法: 第一種通過startService()與stopService()啟動和停止服務,Se

androidfragmentfragment、activityactivity、fragmentactivity之間的通訊

Broadcast廣播接受者可以實現所有通訊;-----------activity與activity之間的通訊--------- **********傳給上一個activity********* //右側+按鈕的點選事件 public void addClick(V

linux程序通訊IPCIPC_PRIVATEftok比較

在linux中,可以使用IPC物件來進行程序間通訊。IPC物件存在於核心中,多程序可以操作同一個IPC物件。 每個IPC物件都有一個唯一的編號,該編號是由系統分配的。那麼不同的程序如何知道這個編號,進而通過它進行通訊呢?下面以共享記憶體為例,進行分析。 方法一:通過f

AndroidServiceActivity的通訊---回撥介面方式

最近在技術交流群中有人問到:要實現service與activity的高強度通訊用什麼方法? 群友回答的是用handler,但面試官好像不太滿意,後來本人查找了下資料,得到個人的結論:service與activity之前的通訊方式有很多,回撥介面方式、觀察者模式、廣播、還有h

androidPowerManager 電源管理,解決滅屏狀態下來簡訊螢幕不會點亮問題

  可解決滅屏狀態下來簡訊螢幕不會點亮問題    PowerManager這個類主要是用來控制電源狀態的. 通過使用該類提供的api可以控制電池的待機時間,一般情況下不要使用。如果確實需要使用,那