編輯:關於 Android 程式設計
IntentService(Service)的使用場景
IntentService 與 Service 的區別
IntentService 的使用
IntentService 原理源碼實現
Service 是 Android 系統中實現程式後台運行的解決方案,非常適合那些不需要與用戶直接互動、且需要長期運行的任務。
由於 Service 運行於 UI 執行緒,因此若想在 Service 中執行耗時操作,就需要在 Service 中建立執行緒來完成。
IntentService 是繼承自 Service、並處理異步請求的一個類,二者的啟動方式並沒有差別。區別在於 IntentService 會自動運行於子執行緒,並且執行完畢後會自行 stop。
總結:若必須在 Service(IntentService)中執行耗時任務,在 Service 中我們必須採用開啟新執行緒的方式(例如 new Thread().start()),且執行完畢要手動退出;而在 IntentService 中則可直接執行,也無需手動干預退出。
一、模擬耗時任務,執行完畢後更新介面 UI。
先來看下效果圖。

點擊耗時任務,啟動 IntentService 模擬耗時任務執行,執行完畢後透過廣播更新介面 UI(也可採用 handler)。
二、程式碼實現。
IntentService
package com.huanjulu.intentservice;/* * Copyright (C) 2016, * Author: huanjulu on 16/6/17 * to: */ import android.app.IntentService; import android.content.Intent; public class TaskIntentService extends IntentService { public TaskIntentService() { super("TaskIntentService-Thread"); } public TaskIntentService(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) { //直接在此執行耗時任務 if (null != intent) { onTashHandler(); } } /** * 模擬耗時任務 如果采用serivce 你就需new Thread 處理 */ private void onTashHandler() { try { Thread.sleep(3000); Intent intent = new Intent(); intent.setAction(MainActivity.TNTENT_SERVICE); sendBroadcast(intent); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); } }
繼承 IntentService 的類至少要實現兩個函數:構造函數與 onHandleIntent() 函數。若要覆蓋 IntentService 的其他函數,注意要透過 super 呼叫父類對應的函數。
此處留意一下 IntentService 的生命週期。我們在 onHandleIntent() 中模擬耗時任務(Thread.sleep(3000),模擬執行時間為 3 秒),執行完畢後發送廣播,通知主介面更新 UI。
Activity 程式碼實現
package com.huanjulu.intentservice; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { public static final String TNTENT_SERVICE = "com.huanjulu.intentservice.TaskIntentService"; TextView textView; private BroadcastReceiver uploadImgReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d("TAG","onReceive"); if (intent.getAction() .equals(TNTENT_SERVICE)) { Log.d("TAG","intent.getAction()"); textView.setText("耗時任務執行完畢!"); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.message_tv); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(TNTENT_SERVICE); registerReceiver(uploadImgReceiver, intentFilter); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setText("正在執行任務..."); Intent intent = new Intent(MainActivity.this, TaskIntentService.class); startService(intent); } }); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(uploadImgReceiver); } }
在 onCreate() 中我們註冊廣播,在 onDestroy() 中註銷,透過點擊事件開啟 IntentService 執行任務。Service 是四大組件之一,所以必須在 AndroidManifest.xml 中聲明。
透過 IntentService 的執行生命週期,第一次執行會先走 onCreate()。
@Override public void onCreate() { super.onCreate(); }
super.onCreate() 呼叫父類(也就是 IntentService)的 onCreate() 函數。
分析一下 IntentService 的 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); }
可以看到主要做了兩件事:一是開啟了一個 HandlerThread 執行緒(關於 HandlerThread 我稍後的博文會分析,這裡只要知道它繼承了 Thread,重點分析 run() 方法);二是透過 mServiceLooper 實例化了 ServiceHandler 對象。
分析 thread.start()。
@Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }
我們看到了什麼?沒錯!實例化 mq、開啟消息循環……依舊是採用 Android 中的異步消息機制。
Looper.prepare(); Looper.loop();
透過 thread.getLooper() 取得實例化的 looper,並作為參數實例化 ServiceHandler()。
private volatile Looper mServiceLooper; private volatile ServiceHandler mServiceHandler; private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { //這裡就是我們IntnetService 中覆寫onHandleIntent 的邏輯 //執行完畢調用stopSelf()自動退出 onHandleIntent((Intent)msg.obj); stopSelf(msg.arg1); } }
有了 looper、實例化了 handler,總得有個 sendMessage 吧。在 onStart 中:
@Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }
流程總結:每次呼叫 onStartCommand 時,onStartCommand 會繼續呼叫 onStart,透過 mServiceHandler 發送一個包含 intent 的消息,然後在該 mServiceHandler 的 handleMessage 中回調 onHandleIntent(intent)。
當觀察者模式與回調機制遇上 Android 源碼
上一篇博客跟大家分享了 Android 源碼中的裝飾者模式,有些意猶未盡,今天接着聊聊 Android 中的觀察者模式,順便說說觀察者模式與回調機制的關係,歡迎大家拍磚。
Android 應用接入微信分享的完整流程
想讓自己的 App 支持一鍵分享到微信,其實並不複雜。只要按照微信開放平台的要求完成幾個步驟,就能讓用戶把網頁、圖文內容分享到微信好友或朋友圈。下面把整個接入過程梳理清楚
百行 Android 程式碼,手寫一個會長高的動畫柱狀圖
做專案的時候碰到一個需求:頁面上要放幾根柱子來展示數據。看似簡單,但仔細一想,柱子的頂端要帶圓角,上方還要浮著數值,最關鍵的是——進場時柱子得一根根「長」起來。單純用 D
Android 開發踩坑筆記:使用 XUtils 框架遇到的那些問題
開發過程中,我接連遇到了兩個令人頭疼的小插曲,這裡記錄下來,也給同樣使用 XUtils 的朋友提個醒。 問題一:Apache HttpClient 找不到 一開始,程式