Android Threads, Handlers and AsyncTask

先看過Processes and Threads會有比較清楚的概念, 當Adnroid Application 啟動後, 系統會建一個主要的thread 稱 “main thread” or “UI thread”, 所有的components 皆跑在這個UI thread, system calls 也是透過UI thread dispatched給各個component, ex: onKeyDown, touch event. UI thread 如因大量運算或等待而blocked, 預設超過5秒ANR(Application Not Responding)就會發生. 且Android UI components 並非thread-safe, 使用上要特別小心. 所以: long time computation使用另外的thread, 不要寫在 UI Thread. 不要在UI thread 之外使用UI component method. 透過Thread, Handler and AsyncTask perform asynchronous processing, 避免UI thread block. Threads Android 提供以下的method, 可在其它的thread 下調用 UI thread. Activity.runOnUiThread(Runnable) View.post(Runnable) <-- used in example code....

June 14, 2012 · 1 min · oopsmonk