Android HandlerThread简介 (1)

2018-06-14  本文已影响3人  假装在去天使之城的路上

What is HandlerThread

HandlerThread is an extension of Thread, which works with a Looper. Meaning, it is meant to handle multiple jobs on the background thread.

What is wrong with Service

Services are executed on the main thread, so they aren't really asynchronous. You have to create a separate thread for them to use if you want them to be asynchronous. With both of these you still have a new thread being created and destroyed.

What is the problem with AsyncTask

AsyncTasks have a single thread dedicated to them, so if you spin off more than one AsyncTask, they aren’t truly asynchronous. This is not necessarily a problem, but it is restrictive if you do want multiple threads. With each AsyncTask that is spun off, a thread is created and destroyed which, if you have a lot of AsyncTasks is a performance issue.

Why not use IntentService

IntentService does use HandlerThread internally (link to source) and this does make them a great option to use. He also points out that there is ever only one instance of a Service in existence at any given time and it has only one HandlerThread. This means that if you need more than one thing to happen at the same time, IntentServices may not be a good option.

Using HandlerThread

Implementation of HandlerThread

HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
handlerThread.start();
Looper looper = handlerThread.getLooper();
Handler handler = new Handler(looper);
Then, in order to use it, you simply have to post Runnable to the Handler thread.

handler.post(new Runnable(){…});

If you want more threads, you’ll have to create more Handlers and HandlerThreads.

Remember to call handlerThread.quit() when you are done with the background thread or on your activities onDestroy() method.

Handler mainHandler = new Handler(context.getMainLooper()); 
 
Runnable myRunnable = new Runnable() {
    @Override  
    public void run() {
        MainActivity.this.onResult();
    } // This is your code 
}; 
mainHandler.post(myRunnable);

Links

HandlerThreads and why you should be using them in your Android apps

Understanding Android Core: Looper, Handler, and HandlerThread

上一篇下一篇

猜你喜欢

热点阅读