編輯:關於android開發
什麼是IntentService?簡單來說IntentService就是一個含有自身消息循環的Service,首先它是一個service,所以service相關具有的特性他都有,同時他還有一些自身的屬性,其內部封裝了一個消息隊列和一個HandlerThread,在其具體的抽象方法:onHandleIntent方法是運行在其消息隊列線程中,廢話不多說,我們來看其簡單的使用方法:
定義一個IntentService
public class MIntentService extends IntentService{
public MIntentService() {
super("");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i("tag", intent.getStringExtra("params") + " " + Thread.currentThread().getId());
}
}
在androidManifest.xml中定義service
啟動這個service
title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MIntentService.class);
intent.putExtra("params", "ceshi");
startService(intent);
}
});
可以發現當點擊title組件的時候,service接收到了消息並打印出了傳遞過去的intent參數,同時顯示onHandlerIntent方法執行的線程ID並非主線程,這是為什麼呢?
下面我們來看一下service的源碼:
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);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public IntentService(String name) {
super();
mName = name;
}
/**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*
*
If enabled is true, * {@link #onStartCommand(Intent, int, int)} will return * {@link Service#START_REDELIVER_INTENT}, so if this process dies before * {@link #onHandleIntent(Intent)} returns, the process will be restarted * and the intent redelivered. If multiple Intents have been sent, only * the most recent one is guaranteed to be redelivered. * *
If enabled is false (the default), * {@link #onStartCommand(Intent, int, int)} will return * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent * dies along with it. */ public void setIntentRedelivery(boolean enabled) { mRedelivery = enabled; } @Override public void onCreate() { // TODO: It would be nice to have an option to hold a partial wakelock // during processing, and to have a static startService(Context, Intent) // method that would launch the service & hand off a wakelock. 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); } /** * 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; } @Override public void onDestroy() { mServiceLooper.quit(); } /** * Unless you provide binding for your service, you don't need to implement this * method, because the default implementation returns null. * @see android.app.Service#onBind */ @Override public IBinder onBind(Intent intent) { return null; } /** * This method is invoked on the worker thread with a request to process. * Only one Intent is processed at a time, but the processing happens on a * worker thread that runs independently from other application logic. * So, if this code takes a long time, it will hold up other requests to * the same IntentService, but it will not hold up anything else. * When all requests have been handled, the IntentService stops itself, * so you should not call {@link #stopSelf}. * * @param intent The value passed to {@link * android.content.Context#startService(Intent)}. */ @WorkerThread protected abstract void onHandleIntent(Intent intent); }
怎麼樣,代碼還是相當的簡潔的,首先通過定義我們可以知道IntentService是一個Service,並且是一個抽象類,所以我們在繼承IntentService的時候需要實現其抽象方法:onHandlerIntent。
下面看一下其onCreate方法:
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
我們可以發現其內部定義一個HandlerIThread(本質上是一個含有消息隊列的線程)
然後用成員變量維護其Looper和Handler,由於其Handler關聯著這個HandlerThread的Looper對象,所以Handler的handMessage方法在HandlerThread線程中執行。
然後我們發現其onStartCommand方法就是調用的其onStart方法,具體看一下其onStart方法:
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
很簡單就是就是講startId和啟動時接受到的intent對象傳遞到消息隊列中處理,那麼我們具體看一下其消息隊列的處理邏輯:
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);
}
}
可以看到起handleMessage方法內部執行了兩個邏輯一個是調用了其onHandlerIntent抽象方法,通過分析其onCreate方法handler對象的創建過程我們知道其handler對象是依附於HandlerThread線程的,所以其handeMessage方法也是在HandlerThread線程中執行的,從而證實了我們剛剛例子中的一個結論,onHandlerIntent在子線程中執行。
然後調用了stopSelf方法,這裡需要注意的是stopSelf方法傳遞了msg.arg1參數,從剛剛的onStart方法我們可以知道我們傳遞了startId,參考其他文章我們知道,由於service可以啟動N次,可以傳遞N次消息,當IntentService的消息隊列中含有消息時調用stopSelf(startId)並不會立即stop自己,只有當消息隊列中最後一個消息被執行完成時才會真正的stop自身。
通過上面的例子與相關說明,我們可以知道:
IntentService是一個service,也是一個抽象類;
繼承IntentService需要實現其onHandlerIntent抽象方法;
onHandlerIntent在子線程中執行;
IntentService內部保存著一個HandlerThread、Looper與Handler等成員變量,維護這自身的消息隊列;
每次IntentService後台任務執行完成之後都會嘗試關閉自身,但是當且僅當IntentService消息隊列中最後一個消息被執行完成之後才會真正的stop自身;
Android開發學習之路-動態高斯模糊怎麼做,android高斯什麼是高斯模糊? 高斯模糊(英語:Gaussian Blur),也叫高斯平滑,是在Adobe Phot
通過百度地圖API顯示當前位置在地圖上(圖標顯示)--第三方開源--百度地圖(二),api當前位置1.下載百度地圖的demo,下載地址:http://lbsyun.bai
Android 配置文件(activity)元素 語法: . . . 被包含在: 可以包含: 描述: 聲明實現了應用程序可視化
Android開發6:Service的使用(簡單音樂播放器的實現),androidservice前言 啦啦啦~各位好久不見啦~博主最近比較忙,而且最近一次實驗也是剛剛