Android: Looper, Handler, HandlerThread. Part I
2015-09-08 17:48
615 查看
What do you know about threads in Android? You may say "I've used
run tasks in background". Nice, but what else? "Oh, I heard something about
because I used them to show toasts from background thread or to post tasks with delay". That's definitely better, but in this post I'll show what's under the hood.
Let's start from looking at the well-known
I bet every Android developer has faced it. First of all, I would like to say that you can find a good overview of
at the official documentation. It's a nice and handy class for running tasks in background if you don't want to waste your time on learning how to manage
Android threads. The only important thing you should know here is that only one method of this class is running on another thread -
The other methods are running on UI thread. Here is a typical use of
We will use the following straightforward
progress bar for our test:
If progress bar freezes, we are doing heavy job on the UI thread.
We are using
get a response from server and we don't want our UI to be blocked while waiting this response, so we delegate this network task to another thread. There are a lot of posts on why using
bad (if it is an inner class of your
it holds an implicit reference to it, which is bad practice, because
be destroyed on configuration change, but they will be kept in memory while worker thread is alive; if it is declared as standalone or static inner class and you are using reference to a
update views, you should always check whether it is
tasks on UI thread (which drives the user interface event loop) are executed in sequential manner, because it makes code more predictable - you are not falling into pitfall of concurrent changes from multiple threads, so if some task is running too long, you'll
get
one-shot task, so it cannot be reused by calling
same instance once again - you should create another instance for a new job.
The interesting part here is that if you try to show a toast from
you'll get an error, something like this:
Why did we face this error? The simple answer: because
be shown only from UI thread, the correct answer: because it can be shown only from thread with
You may ask "What is a
a nice class, but what if the functionality it has is not enough for your needs? If we take a look under the hood of
we will find, that actually it is a box with tightly coupled components:
Let's work with this zoo. Each of you is familiar with threads in
but in
from
should turn your attention to is that the first one incorporates Looper,
a worker, that serves a
a queue that has tasks called messages which should be processed.
through this queue and sends messages to corresponding handlers to process. Any thread can have only one unique
this constraint is achieved by using a concept of ThreadLocal storage. The bundle of
like a pipeline with boxes.
![](https://oscdn.geek-share.com/Uploads/Images/Content/201910/30/e6785440ebe78b1ceeda51ce1f6b8ac1.png)
You may ask "What's the need in all this complexity, if tasks will be processed by their creators -
There are at least 2 advantages:
As mentioned above, it helps you to avoid race conditions, when concurrent threads can make changes and when sequential execution is desired.
completed while thread with
you call
time you want to run a job in background.
You can make a
your own if you want, but I recommend you to use
decided to call it
it already has built-in
you. And what's about
post tasks to the
implicitly associated with thread it was instantiated from via
but you can tie it to another thread by explicitly providing its
the constructor call as well. Now it's time to put all pieces of theory together and look on real
example. Let's imagine we have an
(in this article tasks are represented by the
they actually are will be shown in next part) to its
living on UI thread), but they should be executed with some delay:
Since
the default constructor call) and it is a class member, we have an access to it from inner anonymous classes, and therefore can post tasks to UI thread. We are using
example above and its instance cannot be reused if we want to post a new task, we should create a new one. Is there another solution? Yes, we can use a thread with
Here is a slightly modified previous example with
of
I used
to manage
care of it. Once we started
any time, but remember to call
tied to
You cannot initialize
call, because
thread is not alive yet. Sometimes you can find the following handler initialization technique:
Sometimes it will work fine, but sometimes you'll get
the
Surpise!
![](http://i.imgur.com/U71Ms.gif)
Why does it happen? The trick here is in native call needed for new thread creation. If we take a loop on piece of code, where
called, we will find the following fragment in the
The trick here is that
new thread is created and started. And this call can sometimes happen after your call to the
(you can check it by yourself, just place breakpoints inside
and take a look which one will be hit first), so you can be a victim of race conditions between two threads (main and background). In the next part what these tasks really are inside
be shown.
AsyncTaskto
run tasks in background". Nice, but what else? "Oh, I heard something about
Handlers,
because I used them to show toasts from background thread or to post tasks with delay". That's definitely better, but in this post I'll show what's under the hood.
Let's start from looking at the well-known
AsyncTaskclass,
I bet every Android developer has faced it. First of all, I would like to say that you can find a good overview of
AsyncTaskclass
at the official documentation. It's a nice and handy class for running tasks in background if you don't want to waste your time on learning how to manage
Android threads. The only important thing you should know here is that only one method of this class is running on another thread -
doInBackground.
The other methods are running on UI thread. Here is a typical use of
AsyncTask:
//MyActivity.java public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); MyAsyncTask myTask = new MyAsyncTask(this); myTask.execute("http://developer.android.com"); } } //MyAsyncTask.java public class MyAsyncTask extends AsyncTask<String, Void, Integer> { private Context mContext; public MyAsyncTask(Context context) { mContext = context.getApplicationContext(); } @Override protected void onPreExecute() { Toast.makeText(mContext, "Let's start!", Toast.LENGTH_LONG).show(); } @Override protected Integer doInBackground(String... params) { HttpURLConnection connection; try { connection = (HttpURLConnection) new URL(params[0]) .openConnection(); return connection.getResponseCode(); } catch (IOException e) { e.printStackTrace(); } return -1; } @Override protected void onPostExecute(Integer integer) { if (integer != -1) { Toast.makeText(mContext, "Got the following code: " + integer, Toast.LENGTH_LONG).show(); } } }
We will use the following straightforward
mainlayout with
progress bar for our test:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center"> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progressBar"/> </LinearLayout>
If progress bar freezes, we are doing heavy job on the UI thread.
We are using
AsyncTaskhere, because it takes some time to
get a response from server and we don't want our UI to be blocked while waiting this response, so we delegate this network task to another thread. There are a lot of posts on why using
AsyncTaskis
bad (if it is an inner class of your
Activity/
Fragment,
it holds an implicit reference to it, which is bad practice, because
Activity/
Fragmentcan
be destroyed on configuration change, but they will be kept in memory while worker thread is alive; if it is declared as standalone or static inner class and you are using reference to a
Contextto
update views, you should always check whether it is
nullor not). All
tasks on UI thread (which drives the user interface event loop) are executed in sequential manner, because it makes code more predictable - you are not falling into pitfall of concurrent changes from multiple threads, so if some task is running too long, you'll
get
ANR(Application Not Responding) warning.
AsyncTaskis
one-shot task, so it cannot be reused by calling
executemethod on the
same instance once again - you should create another instance for a new job.
The interesting part here is that if you try to show a toast from
doInBackgroundmethod
you'll get an error, something like this:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.<init>(Handler.java:121) at android.widget.Toast$TN.<init>(Toast.java:322) at android.widget.Toast.<init>(Toast.java:91) at android.widget.Toast.makeText(Toast.java:238) at com.example.testapp.MyActivity$MyAsyncTask.doInBackground(MyActivity.java:25) at com.example.testapp.MyActivity$MyAsyncTask.doInBackground(MyActivity.java:21)
Why did we face this error? The simple answer: because
Toastcan
be shown only from UI thread, the correct answer: because it can be shown only from thread with
Looper.
You may ask "What is a
Looper?". Ok, it's time to dig deeper.
AsyncTaskis
a nice class, but what if the functionality it has is not enough for your needs? If we take a look under the hood of
AsyncTask,
we will find, that actually it is a box with tightly coupled components:
Handler,
Runnable,
Thread.
Let's work with this zoo. Each of you is familiar with threads in
Java,
but in
Androidyou may find one more class HandlerThread derived
from
Thread. The only significant difference between
HandlerThreadand
Threadyou
should turn your attention to is that the first one incorporates Looper,
ThreadandMessageQueue.
Looperis
a worker, that serves a
MessageQueuefor a current thread.
MessageQueueis
a queue that has tasks called messages which should be processed.
Looperloops
through this queue and sends messages to corresponding handlers to process. Any thread can have only one unique
Looper,
this constraint is achieved by using a concept of ThreadLocal storage. The bundle of
Looper+
MessageQueueis
like a pipeline with boxes.
![](https://oscdn.geek-share.com/Uploads/Images/Content/201910/30/e6785440ebe78b1ceeda51ce1f6b8ac1.png)
You may ask "What's the need in all this complexity, if tasks will be processed by their creators -
Handlers?".
There are at least 2 advantages:
As mentioned above, it helps you to avoid race conditions, when concurrent threads can make changes and when sequential execution is desired.
Threadcannot be reused after the job is
completed while thread with
Looperis kept alive by
Looperuntil
you call
quitmethod, so you don't need to create a new instance each
time you want to run a job in background.
You can make a
Threadwith
Looperon
your own if you want, but I recommend you to use
HandlerThread(Google
decided to call it
HandlerThreadinstead of
LooperThread):
it already has built-in
Looperand all pre-setup job will be done for
you. And what's about
Handler? It is a class with 2 basic functions:
post tasks to the
MessageQueueand process them. By default,
Handleris
implicitly associated with thread it was instantiated from via
Looper,
but you can tie it to another thread by explicitly providing its
Looperat
the constructor call as well. Now it's time to put all pieces of theory together and look on real
example. Let's imagine we have an
Activityand we want to post tasks
(in this article tasks are represented by the
Runnableinterface, what
they actually are will be shown in next part) to its
MessageQueue(all
Activitiesand
Fragmentsare
living on UI thread), but they should be executed with some delay:
public class MyActivity extends Activity { private Handler mUiHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Thread myThread = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 4; i++) { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } if (i == 2) { mUiHandler.post(new Runnable() { @Override public void run() { Toast.makeText(MyActivity.this, "I am at the middle of background task", Toast.LENGTH_LONG) .show(); } }); } } mUiHandler.post(new Runnable() { @Override public void run() { Toast.makeText(MyActivity.this, "Background task is completed", Toast.LENGTH_LONG) .show(); } }); } }); myThread.start(); } }
Since
mUiHandleris tied up to UI thread (it gets UI thread
Looperat
the default constructor call) and it is a class member, we have an access to it from inner anonymous classes, and therefore can post tasks to UI thread. We are using
Threadin
example above and its instance cannot be reused if we want to post a new task, we should create a new one. Is there another solution? Yes, we can use a thread with
Looper.
Here is a slightly modified previous example with
HandlerThreadinstead
of
Thread, which demonstrates its ability to be reused:
//MyActivity.java public class MyActivity extends Activity { private Handler mUiHandler = new Handler(); private MyWorkerThread mWorkerThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mWorkerThread = new MyWorkerThread("myWorkerThread"); Runnable task = new Runnable() { @Override public void run() { for (int i = 0; i < 4; i++) { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } if (i == 2) { mUiHandler.post(new Runnable() { @Override public void run() { Toast.makeText(MyActivity.this, "I am at the middle of background task", Toast.LENGTH_LONG) .show(); } }); } } mUiHandler.post(new Runnable() { @Override public void run() { Toast.makeText(MyActivity.this, "Background task is completed", Toast.LENGTH_LONG) .show(); } }); } }; mWorkerThread.start(); mWorkerThread.prepareHandler(); mWorkerThread.postTask(task); mWorkerThread.postTask(task); } @Override protected void onDestroy() { mWorkerThread.quit(); super.onDestroy(); } } //MyWorkerThread.java public class MyWorkerThread extends HandlerThread { private Handler mWorkerHandler; public MyWorkerThread(String name) { super(name); } public void postTask(Runnable task){ mWorkerHandler.post(task); } public void prepareHandler(){ mWorkerHandler = new Handler(getLooper()); } }
I used
HandlerThreadin this example, because I don't want
to manage
Looperby myself,
HandlerThreadtakes
care of it. Once we started
HandlerThreadwe can post tasks to it at
any time, but remember to call
quitwhen you want to stop
HandlerThread.
mWorkerHandleris
tied to
MyWorkerThreadby specifying its
Looper.
You cannot initialize
mWorkerHandlerat the
HandlerThreadconstructor
call, because
getLooperwill return
nullsince
thread is not alive yet. Sometimes you can find the following handler initialization technique:
private class MyWorkerThread extends HandlerThread { private Handler mWorkerHandler; public MyWorkerThread(String name) { super(name); } @Override protected void onLooperPrepared() { mWorkerHandler = new Handler(getLooper()); } public void postTask(Runnable task){ mWorkerHandler.post(task); } }
Sometimes it will work fine, but sometimes you'll get
NPEat
the
postTaskcall stating, that
mWorkerHandleris
null.
Surpise!
![](http://i.imgur.com/U71Ms.gif)
Why does it happen? The trick here is in native call needed for new thread creation. If we take a loop on piece of code, where
onLooperPreparedis
called, we will find the following fragment in the
HandlerThreadclass:
public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }
The trick here is that
runmethod will be called only after
new thread is created and started. And this call can sometimes happen after your call to the
postTaskmethod
(you can check it by yourself, just place breakpoints inside
postTaskand
onLooperPreparedmethods
and take a look which one will be hit first), so you can be a victim of race conditions between two threads (main and background). In the next part what these tasks really are inside
MessageQueuewill
be shown.
相关文章推荐
- android下拉刷新android-Ultra-Pull-To-Refresh使用
- 最近开发中的一些坑#1
- 【Android Studio简易教程】断点调试及相关技巧
- Android中Context的理解与使用技巧
- Android客户端与服务器端通过DES加密认证
- 在百度地图的基础上增加了实时定位和轨迹
- android序列化Serializable、Parcelable(一)
- Android 动态添加每条输入的内容
- Android下拉刷新SwipeRefreshLayout
- Android笔记:20150823
- Android笔记:20150824(this关键字的使用)
- Android笔记:20150820
- 【第四篇章-android平台MediaCodec】根据编码类型MIME_TYPE获取MediaCodecInfo
- Android笔记:20150408
- Android笔记:20150414
- Android客户端写Cookie和内嵌的网页实现登录状态的同步
- Android笔记:20150406
- 基于xmpp openfire smack开发之Android消息推送技术原理分析和实践[4]
- Android笔记(二十四)广播机制
- Android笔记:20150308