Android: Looper, Handler, HandlerThread. Part I

What do you know about threads in Android? You may say "I've used AsyncTask to 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 AsyncTask class, I bet every Android developer has faced it. First of all, I would like to say that you can find a good overview of AsyncTask class 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 main layout 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 AsyncTask here, 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 AsyncTask is bad (if it is an inner class of your Activity/Fragment, it holds an implicit reference to it, which is bad practice, because Activity/Fragment can 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 Context to update views, you should always check whether it is null or 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. AsyncTask is one-shot task, so it cannot be reused by calling execute method 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 doInBackground method 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 Toast can 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. AsyncTask is 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: HandlerRunnableThread. 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 HandlerThread and Thread you should turn your attention to is that the first one incorporates LooperThread andMessageQueueLooper is a worker, that serves a MessageQueue for a current thread. MessageQueue is a queue that has tasks called messages which should be processed. Looper loops 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+MessageQueue is like a pipeline with boxes.

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.
  • Thread cannot be reused after the job is completed while thread with Looper is kept alive by Looper until you call quit method, so you don't need to create a new instance each time you want to run a job in background.

You can make a Thread with Looper on your own if you want, but I recommend you to use HandlerThread (Google decided to call it HandlerThread instead of LooperThread): it already has built-in Looper and 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 MessageQueue and process them. By default, Handler is implicitly associated with thread it was instantiated from via Looper, but you can tie it to another thread by explicitly providing its Looper at 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 Activity and we want to post tasks (in this article tasks are represented by the Runnable interface, what they actually are will be shown in next part) to its MessageQueue (all Activities and Fragments are 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 mUiHandler is tied up to UI thread (it gets UI thread Looper at 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 Thread in 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 HandlerThread instead 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 HandlerThread in this example, because I don't want to manage Looper by myself, HandlerThread takes care of it. Once we started HandlerThread we can post tasks to it at any time, but remember to call quit when you want to stop HandlerThreadmWorkerHandler is tied to MyWorkerThread by specifying its Looper. You cannot initialize mWorkerHandler at the HandlerThread constructor call, because getLooper will return null since 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 NPE at the postTask call stating, that mWorkerHandler is null. Surpise!

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 onLooperPrepared is called, we will find the following fragment in the HandlerThread class:

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 run method will be called only after new thread is created and started. And this call can sometimes happen after your call to the postTask method (you can check it by yourself, just place breakpoints inside postTask and onLooperPrepared methods 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 MessageQueue will be shown.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
蛋白质是生物体中普遍存在的一类重要生物大分子,由天然氨基酸通过肽键连接而成。它具有复杂的分子结构和特定的生物功能,是表达生物遗传性状的一类主要物质。 蛋白质的结构可分为四级:一级结构是组成蛋白质多肽链的线性氨基酸序列;二级结构是依靠不同氨基酸之间的C=O和N-H基团间的氢键形成的稳定结构,主要为α螺旋和β折叠;三级结构是通过多个二级结构元素在三维空间的排列所形成的一个蛋白质分子的三维结构;四级结构用于描述由不同多肽链(亚基)间相互作用形成具有功能的蛋白质复合物分子。 蛋白质在生物体内具有多种功能,包括提供能量、维持电解质平衡、信息交流、构成人的身体以及免疫等。例如,蛋白质分解可以为人体提供能量,每克蛋白质能产生4千卡的热能;血液里的蛋白质能帮助维持体内的酸碱平衡和血液的渗透压;蛋白质是组成人体器官组织的重要物质,可以修复受损的器官功能,以及维持细胞的生长和更新;蛋白质也是构成多种生理活性的物质,如免疫球蛋白,具有维持机体正常免疫功能的作用。 蛋白质的合成是指生物按照从脱氧核糖核酸(DNA)转录得到的信使核糖核酸(mRNA)上的遗传信息合成蛋白质的过程。这个过程包括氨基酸的活化、多肽链合成的起始、肽链的延长、肽链的终止和释放以及蛋白质合成后的加工修饰等步骤。 蛋白质降解是指食物中的蛋白质经过蛋白质降解酶的作用降解为多肽和氨基酸然后被人体吸收的过程。这个过程在细胞的生理活动中发挥着极其重要的作用,例如将蛋白质降解后成为小分子的氨基酸,并被循环利用;处理错误折叠的蛋白质以及多余组分,使之降解,以防机体产生错误应答。 总的来说,蛋白质是生物体内不可或缺的一类重要物质,对于维持生物体的正常生理功能具有至关重要的作用。
06-08 10:58:36.121 1815 1815 E AndroidRuntime: Process: com.android.settings, PID: 1815 06-08 10:58:36.121 1815 1815 E AndroidRuntime: java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.wifi.supplicant.STATE_CHANGE flg=0x10 (has extras) } in com.android.settings.m8settings.receiver.WifiReceiver@41c8a5c 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$android-app-LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1830) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at android.app.LoadedApk$ReceiverDispatcher$Args$$ExternalSyntheticLambda0.run(Unknown Source:2) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:942) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at android.os.Looper.loopOnce(Looper.java:201) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at android.os.Looper.loop(Looper.java:288) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:8061) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:703) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:911) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.wifi.SupplicantState.name()' on a null object reference 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at com.android.settings.m8settings.receiver.WifiReceiver.onReceive(WifiReceiver.java:46) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$android-app-LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1820) 06-08 10:58:36.121 1815 1815 E AndroidRuntime: ... 9 more
06-09

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值