#### 11.2.4 IntentService
參考:
[擴展 IntentService 類](https://developer.android.google.cn/guide/components/services#ExtendingIntentService)
```
package android.app;
import android.annotation.WorkerThread;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
public IntentService(String name) {
super();
mName = name;
}
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@WorkerThread
protected abstract void onHandleIntent(Intent intent);
}
```
[IntentService](https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/core/java/android/app/IntentService.java)是一種特殊的Service,它**繼承了Service并且它是一個抽象類**,因此**必須創建它的子類才能使用IntentService**。IntentService可用于**執行后臺耗時的任務,當任務執行后它會自動停止**,同時由于IntentService是服務的原因,這導致**它的優先級比單純的線程要高很多**,所以IntentService**比較適合執行一些高優先級的后臺任務,因為它優先級高不容易被系統殺死**。在實現上,**IntentService封裝了HandlerThread和Handler**,這一點可以從它的onCreate方法中看出來,如下所示。
```
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
```
**當IntentService被第一次啟動時,它的onCreate方法會被調用,onCreate方法會創建一個HandlerThread,然后使用它的Looper來構造一個Handler對象mServiceHandler,這樣通過mServiceHandler發送的消息最終都會在HandlerThread中執行**,從這個角度來看,**IntentService也可以用于執行后臺任務**。
**每次啟動IntentService,它的onStartCommand方法就會調用一次,IntentService在onStartCommand中處理每個后臺任務的Intent**。
下面看一下**onStartCommand方法是如何處理外界的Intent的**,onStartCommand調用了onStart,onStart方法的實現如下所示。
```
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
```
可以看出,**IntentService僅僅是通過mServiceHandler發送了一個消息,這個消息會在HandlerThread中被處理。mServiceHandler收到消息后,會將Intent對象傳遞給onHandleIntent方法(從該方法的注釋可以看出,IntentService被啟動后,會調用該方法)去處理**。
注意:**這個Intent對象的內容和外界的startService(intent)中的intent的內容是完全一致的,通過這個Intent對象即可解析出外界啟動IntentService時所傳遞的參數,通過這些參數就可以區分具體的后臺任務,這樣在onHandleIntent方法中就可以對不同的后臺任務做處理了**。
當**onHandleIntent方法執行結束后,IntentService會通過stopSelf(int startId)方法來嘗試停止服務**。這里之所以采用stopSelf(int startId)而不是stopSelf()來停止服務,那是因為**stopSelf()會立刻停止服務,而這個時候可能還有其他消息未處理,stopSelf(int startId)則會等待所有的消息都處理完畢后才終止服務。一般來說,stopSelf(int startId)在嘗試停止服務之前會判斷最近啟動服務的次數是否和startId相等,如果相等就立刻停止服務,不相等則不停止服務,這個策略可以從AMS的stopServiceToken方法的實現中找到依據**,讀者感興趣的話可以自行查看源碼實現。ServiceHandler的實現如下所示。
```
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
```
IntentService的**onHandleIntent方法是一個抽象方法,它需要我們在子類中實現**,它的**作用是從Intent參數中區分具體的任務并執行這些任務**。
* 如果目前**只存在一個后臺任務**,那么onHandleIntent方法**執行完這個任務后,stopSelf(int startId)就會直接停止服務**;
* 如果目前**存在多個后臺任務**,那么當onHandleIntent方法**執行完最后一個任務時,stopSelf(int startId)才會直接停止服務**。
另外,**由于每執行一個后臺任務就必須啟動一次IntentService,而IntentService內部則通過消息的方式向HandlerThread請求執行任務,Handler中的Looper是順序處理消息的,這就意味著IntentService也是順序執行后臺任務的,當有多個后臺任務同時存在時,這些后臺任務會按照外界發起的順序排隊執行**。
* [ ] 示例
下面通過一個示例來進一步說明IntentService的工作方式,首先派生一個IntentService的子類,比如LocalIntentService,它的實現如下所示。
public class LocalIntentService extends IntentService {
private static final String TAG = "LocalIntentService";
public LocalIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getStringExtra("task_action");
Log.d(TAG, "receive task :" + action);
SystemClock.sleep(3000);
if ("com.ryg.action.TASK1".equals(action)) {
Log.d(TAG, "handle task: " + action);
}
}
@Override
public void onDestroy() {
Log.d(TAG, "service destroyed.");
super.onDestroy();
}
}
這里對LocalIntentService的實現做一下簡單的說明。**在onHandleIntent方法中會從參數中解析出后臺任務的標識,即task_action字段所代表的內容,然后根據不同的任務標識來執行具體的后臺任務**。這里為了簡單起見,直接通過SystemClock.sleep(3000)來休眠3000毫秒從而模擬一種耗時的后臺任務,**另外為了驗證IntentService的停止時機,這里在onDestroy()中打印了一句日志**。LocalIntentService實現完成了以后,就可以在外界請求執行后臺任務了,在下面的代碼中先后發起了3個后臺任務的請求:
```
Intent service = new Intent(this, LocalIntentService.class);
service.putExtra("task_action", "com.ryg.action.TASK1");
startService(service);
service.putExtra("task_action", "com.ryg.action.TASK2");
startService(service);
service.putExtra("task_action", "com.ryg.action.TASK3");
startService(service);
```
運行程序,觀察日志,如下所示。
```
05-17 17:08:23.186 E/dalvikvm(25793): threadid=11: calling run(), name=
IntentService[LocalIntentService]
05-17 17:08:23.196 D/LocalIntentService(25793): receive task :com.ryg.action.TASK1
05-17 17:08:26.199 D/LocalIntentService(25793): handle task: com.ryg.action.TASK1
05-17 17:08:26.199 D/LocalIntentService(25793): receive task :com.ryg.action.TASK2
05-17 17:08:29.192 D/LocalIntentService(25793): receive task :com.ryg.action.TASK3
05-17 17:08:32.205 D/LocalIntentService(25793): service destroyed.
05-17 17:08:32.205 E/dalvikvm(25793): threadid=11: exiting, name=
IntentService[LocalIntentService]
```
從上面的日志可以看出,**三個后臺任務是排隊執行的,它們的執行順序就是它們發起請求對的順序,即TASK1、TASK2、TASK3**。
另外一點就是**當TASK3執行完畢后,LocalIntentService才真正地停止,從日志中可以看出LocalIntentService執行了`onDestroy()`,這也意味著服務正在停止**。
- 前言
- 第1章 Activity的生命周期和啟動模式
- 1.1 Activity的生命周期全面分析
- 1.1.1 典型情況下的生命周期分析
- 1.1.2 異常情況下的生命周期分析
- 1.2 Activity的啟動模式
- 1.2.1 Activity的LaunchMode
- 1.2.2 Activity的Flags
- 1.3 IntentFilter的匹配規則
- 第2章 IPC機制
- 2.1 Android IPC簡介
- 2.2 Android中的多進程模式
- 2.2.1 開啟多進程模式
- 2.2.2 多進程模式的運行機制
- 2.3 IPC基礎概念介紹
- 2.3.1 Serializable接口
- 2.3.2 Parcelable接口
- 2.3.3 Binder
- 2.4 Android中的IPC方式
- 2.4.1 使用Bundle
- 2.4.2 使用文件共享
- 2.4.3 使用Messenger
- 2.4.4 使用AIDL
- 2.4.5 使用ContentProvider
- 2.4.6 使用Socket
- 2.5 Binder連接池
- 2.6 選用合適的IPC方式
- 第3章 View的事件體系
- 3.1 View基礎知識
- 3.1.1 什么是View
- 3.1.2 View的位置參數
- 3.1.3 MotionEvent和TouchSlop
- 3.1.4 VelocityTracker、GestureDetector和Scroller
- 3.2 View的滑動
- 3.2.1 使用scrollTo/scrollBy
- 3.2.2 使用動畫
- 3.2.3 改變布局參數
- 3.2.4 各種滑動方式的對比
- 3.3 彈性滑動
- 3.3.1 使用Scroller7
- 3.3.2 通過動畫
- 3.3.3 使用延時策略
- 3.4 View的事件分發機制
- 3.4.1 點擊事件的傳遞規則
- 3.4.2 事件分發的源碼解析
- 3.5 View的滑動沖突
- 3.5.1 常見的滑動沖突場景
- 3.5.2 滑動沖突的處理規則
- 3.5.3 滑動沖突的解決方式
- 第4章 View的工作原理
- 4.1 初識ViewRoot和DecorView
- 4.2 理解MeasureSpec
- 4.2.1 MeasureSpec
- 4.2.2 MeasureSpec和LayoutParams的對應關系
- 4.3 View的工作流程
- 4.3.1 measure過程
- 4.3.2 layout過程
- 4.3.3 draw過程
- 4.4 自定義View
- 4.4.1 自定義View的分類
- 4.4.2 自定義View須知
- 4.4.3 自定義View示例
- 4.4.4 自定義View的思想
- 第5章 理解RemoteViews
- 5.1 RemoteViews的應用
- 5.1.1 RemoteViews在通知欄上的應用
- 5.1.2 RemoteViews在桌面小部件上的應用
- 5.1.3 PendingIntent概述
- 5.2 RemoteViews的內部機制
- 5.3 RemoteViews的意義
- 第6章 Android的Drawable
- 6.1 Drawable簡介
- 6.2 Drawable的分類
- 6.2.1 BitmapDrawable2
- 6.2.2 ShapeDrawable
- 6.2.3 LayerDrawable
- 6.2.4 StateListDrawable
- 6.2.5 LevelListDrawable
- 6.2.6 TransitionDrawable
- 6.2.7 InsetDrawable
- 6.2.8 ScaleDrawable
- 6.2.9 ClipDrawable
- 6.3 自定義Drawable
- 第7章 Android動畫深入分析
- 7.1 View動畫
- 7.1.1 View動畫的種類
- 7.1.2 自定義View動畫
- 7.1.3 幀動畫
- 7.2 View動畫的特殊使用場景
- 7.2.1 LayoutAnimation
- 7.2.2 Activity的切換效果
- 7.3 屬性動畫
- 7.3.1 使用屬性動畫
- 7.3.2 理解插值器和估值器 /
- 7.3.3 屬性動畫的監聽器
- 7.3.4 對任意屬性做動畫
- 7.3.5 屬性動畫的工作原理
- 7.4 使用動畫的注意事項
- 第8章 理解Window和WindowManager
- 8.1 Window和WindowManager
- 8.2 Window的內部機制
- 8.2.1 Window的添加過程
- 8.2.2 Window的刪除過程
- 8.2.3 Window的更新過程
- 8.3 Window的創建過程
- 8.3.1 Activity的Window創建過程
- 8.3.2 Dialog的Window創建過程
- 8.3.3 Toast的Window創建過程
- 第9章 四大組件的工作過程
- 9.1 四大組件的運行狀態
- 9.2 Activity的工作過程
- 9.3 Service的工作過程
- 9.3.1 Service的啟動過程
- 9.3.2 Service的綁定過程
- 9.4 BroadcastReceiver的工作過程
- 9.4.1 廣播的注冊過程
- 9.4.2 廣播的發送和接收過程
- 9.5 ContentProvider的工作過程
- 第10章 Android的消息機制
- 10.1 Android的消息機制概述
- 10.2 Android的消息機制分析
- 10.2.1 ThreadLocal的工作原理
- 10.2.2 消息隊列的工作原理
- 10.2.3 Looper的工作原理
- 10.2.4 Handler的工作原理
- 10.3 主線程的消息循環
- 第11章 Android的線程和線程池
- 11.1 主線程和子線程
- 11.2 Android中的線程形態
- 11.2.1 AsyncTask
- 11.2.2 AsyncTask的工作原理
- 11.2.3 HandlerThread
- 11.2.4 IntentService
- 11.3 Android中的線程池
- 11.3.1 ThreadPoolExecutor
- 11.3.2 線程池的分類
- 第12章 Bitmap的加載和Cache
- 12.1 Bitmap的高效加載
- 12.2 Android中的緩存策略
- 12.2.1 LruCache
- 12.2.2 DiskLruCache
- 12.2.3 ImageLoader的實現446
- 12.3 ImageLoader的使用
- 12.3.1 照片墻效果
- 12.3.2 優化列表的卡頓現象
- 第13章 綜合技術
- 13.1 使用CrashHandler來獲取應用的crash信息
- 13.2 使用multidex來解決方法數越界
- 13.3 Android的動態加載技術
- 13.4 反編譯初步
- 13.4.1 使用dex2jar和jd-gui反編譯apk
- 13.4.2 使用apktool對apk進行二次打包
- 第14章 JNI和NDK編程
- 14.1 JNI的開發流程
- 14.2 NDK的開發流程
- 14.3 JNI的數據類型和類型簽名
- 14.4 JNI調用Java方法的流程
- 第15章 Android性能優化
- 15.1 Android的性能優化方法
- 15.1.1 布局優化
- 15.1.2 繪制優化
- 15.1.3 內存泄露優化
- 15.1.4 響應速度優化和ANR日志分析
- 15.1.5 ListView和Bitmap優化
- 15.1.6 線程優化
- 15.1.7 一些性能優化建議
- 15.2 內存泄露分析之MAT工具
- 15.3 提高程序的可維護性