使用intentService與service有什麼不同呢

(1)直接 創建一個默認的工作線程,該線程執行所有的intent傳遞給onStartCommand()區別於應用程序的主線程。

 (2)直接創建一個工作隊列,將一個意圖傳遞給你onHandleIntent()的實現,所以我們就永遠不必擔心多線程。

 (3)當請求完成後自己會調用stopSelf(),所以你就不用調用該方法了。

 (4)提供的默認實現onBind()返回null,所以也不需要重寫這個方法。so easy啊

 (5)提供了一個默認實現onStartCommand(),將意圖工作隊列,然後發送到你onHandleIntent()實現。

 我們需要做的就是實現onHandlerIntent()方法,還有一點就是經常被遺忘的,構造函數是必需的,而且必須調用超IntentService(字符串) ,因爲工作線程的構造函數必須使用一個名稱。如何實現呢,我們藉助於谷歌官方文檔來看一下吧。


  1. public class HelloIntentService extends IntentService {    
  2.     
  3.   /**  
  4.    * A constructor is required, and must call the super IntentService(String)  
  5.    * constructor with a name for the worker thread.  
  6.    */    
  7.   public HelloIntentService() {    
  8.       super("HelloIntentService");    
  9.   }    
  10.     
  11.   /**  
  12.    * The IntentService calls this method from the default worker thread with  
  13.    * the intent that started the service. When this method returns, IntentService  
  14.    * stops the service, as appropriate.  
  15.    */    
  16.   @Override    
  17.   protected void onHandleIntent(Intent intent) {    
  18.       // Normally we would do some work here, like download a file.    
  19.       // For our sample, we just sleep for 5 seconds.    
  20.       long endTime = System.currentTimeMillis() + 5*1000;    
  21.       while (System.currentTimeMillis() < endTime) {    
  22.           synchronized (this) {    
  23.               try {    
  24.                   wait(endTime - System.currentTimeMillis());    
  25.               } catch (Exception e) {    
  26.               }    
  27.           }    
  28.       }    
  29.   }    
  30. }   

那麼它爲什麼不用stopself()方法呢,我們看一下自身的源代碼把


  1. public abstract class IntentService extends Service {    
  2.     private volatile Looper mServiceLooper;    
  3.     private volatile ServiceHandler mServiceHandler;    
  4.     private String mName;    
  5.     private boolean mRedelivery;    
  6.     
  7.     private final class ServiceHandler extends Handler {    
  8.         public ServiceHandler(Looper looper) {    
  9.             super(looper);    
  10.         }    
  11.     
  12.         @Override    
  13.         public void handleMessage(Message msg) {    
  14.             onHandleIntent((Intent)msg.obj);    
  15.             stopSelf(msg.arg1);    
  16.         }    
  17.     }    
  18.     
  19.     /**  
  20.      * Creates an IntentService.  Invoked by your subclass's constructor.  
  21.      *  
  22.      * @param name Used to name the worker thread, important only for debugging.  
  23.      */    
  24.     public IntentService(String name) {    
  25.         super();    
  26.         mName = name;    
  27.     }    
  28.     
  29.     /**  
  30.      * Sets intent redelivery preferences.  Usually called from the constructor  
  31.      * with your preferred semantics.  
  32.      *  
  33.      * <p>If enabled is true,  
  34.      * {@link #onStartCommand(Intent, int, int)} will return  
  35.      * {@link Service#START_REDELIVER_INTENT}, so if this process dies before  
  36.      * {@link #onHandleIntent(Intent)} returns, the process will be restarted  
  37.      * and the intent redelivered.  If multiple Intents have been sent, only  
  38.      * the most recent one is guaranteed to be redelivered.  
  39.      *  
  40.      * <p>If enabled is false (the default),  
  41.      * {@link #onStartCommand(Intent, int, int)} will return  
  42.      * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent  
  43.      * dies along with it.  
  44.      */    
  45.     public void setIntentRedelivery(boolean enabled) {    
  46.         mRedelivery = enabled;    
  47.     }    
  48.     
  49.     @Override    
  50.     public void onCreate() {    
  51.         // TODO: It would be nice to have an option to hold a partial wakelock    
  52.         // during processing, and to have a static startService(Context, Intent)    
  53.         // method that would launch the service & hand off a wakelock.    
  54.     
  55.         super.onCreate();    
  56.         HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");    
  57.         thread.start();    
  58.     
  59.         mServiceLooper = thread.getLooper();    
  60.         mServiceHandler = new ServiceHandler(mServiceLooper);    
  61.     }    
  62.     
  63.     @Override    
  64.     public void onStart(Intent intent, int startId) {    
  65.         Message msg = mServiceHandler.obtainMessage();    
  66.         msg.arg1 = startId;    
  67.         msg.obj = intent;    
  68.         mServiceHandler.sendMessage(msg);    
  69.     }    
  70.     
  71.     /**  
  72.      * You should not override this method for your IntentService. Instead,  
  73.      * override {@link #onHandleIntent}, which the system calls when the IntentService  
  74.      * receives a start request.  
  75.      * @see android.app.Service#onStartCommand  
  76.      */    
  77.     @Override    
  78.     public int onStartCommand(Intent intent, int flags, int startId) {    
  79.         onStart(intent, startId);    
  80.         return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;    
  81.     }    
  82.     
  83.     @Override    
  84.     public void onDestroy() {    
  85.         mServiceLooper.quit();    
  86.     }    
  87.     
  88.     /**  
  89.      * Unless you provide binding for your service, you don't need to implement this  
  90.      * method, because the default implementation returns null.   
  91.      * @see android.app.Service#onBind  
  92.      */    
  93.     @Override    
  94.     public IBinder onBind(Intent intent) {    
  95.         return null;    
  96.     }    
  97.     
  98.     /**  
  99.      * This method is invoked on the worker thread with a request to process.  
  100.      * Only one Intent is processed at a time, but the processing happens on a  
  101.      * worker thread that runs independently from other application logic.  
  102.      * So, if this code takes a long time, it will hold up other requests to  
  103.      * the same IntentService, but it will not hold up anything else.  
  104.      * When all requests have been handled, the IntentService stops itself,  
  105.      * so you should not call {@link #stopSelf}.  
  106.      *  
  107.      * @param intent The value passed to {@link  
  108.      *               android.content.Context#startService(Intent)}.  
  109.      */    
  110.     protected abstract void onHandleIntent(Intent intent);    
  111. }    

我們可以看到源代碼裏頭的第15行handlerMessage方法裏當處理完請求後就會調用stopself()方法了,外界就不用調用了,此外還有一點我們可以看到代碼最後一行第110行,onhandleIntent()是一個抽象類,而其他類都是抽象類,所以我們就可以理解爲什麼只需要重寫onhandleIntent()方法了吧。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章