Android time-consuming task _ HandlerThread

Source: Internet
Author: User

Android time-consuming task _ HandlerThread
In the previous android time-consuming task _ handler, HandlerThread introduced the operating mechanism of handler, and introduced a simple example of logoff in a common thread and communication using the handler mechanism. We know that there is no logoff in a common thread, so it is difficult to use the handler mechanism in a common thread space. If we do this every time, it will be a little troublesome. In fact, Android has encapsulated a thread HandlerThread with its own logoff. Its implementation is basically the same as the example given in the previous article, but it is more professional. The following is the detailed code of this class.

public class HandlerThread extends Thread {    private int mPriority;      private int mTid =-1;     private Looper mLooper;      publicHandlerThread(String name) {        super(name);        mPriority =Process.THREAD_PRIORITY_DEFAULT;    }     publicHandlerThread(String name, int priority) {        super(name);        mPriority =priority;    }     protected void onLooperPrepared() {    }     public void run() {        mTid =Process.myTid();        Looper.prepare();        synchronized(this) {            mLooper =Looper.myLooper();            notifyAll();           }       Process.setThreadPriority(mPriority);       onLooperPrepared();        Looper.loop();          mTid = -1;    }     public Looper getLooper() {        if (!isAlive()) {            return null;        }         // If the threadhas been started, wait until the looper has been created.        synchronized(this) {            while(isAlive() && mLooper == null) {                try {                   wait();                } catch(InterruptedException e) {                }            }        }        return mLooper;    }     public boolean quit(){        Looper looper =getLooper();        if (looper !=null) {           looper.quit();            return true;        }        return false;    }     public intgetThreadId() {        return mTid;    }}
This class inherits the Thread class. When using this class, you must pay attention to start (). Otherwise, the run () method is not called and the handler mechanism is not established.
A classic application of HandlerThread is an application in the service. We know that the service is generally running in the main thread, in android time-consuming task _ ANR, I also recommend that you start the service in BroadcastReceiver and start the thread in the service to process time-consuming tasks. Here is a typical code for how to start a thread:

 

Public class BackService extends Service {private ServiceHandler serviceHandler; @ Overridepublic IBinder onBind (Intent arg0) {return null;} private final class ServiceHandler extends Handler {public ServiceHandler (Looper loinder) {super (logoff) ;}@ Overridepublic void handleMessage (Message msg) {super. handleMessage (msg); onHandleIntent (Intent) msg. obj); // The service is stopped only when the startId parameter is the same as the ID generated when the service is last started. StopSelf (msg. arg1) ;}@ Overridepublic void onCreate () {super. onCreate (); HandlerThread thread = new HandlerThread ("BackService"); thread. start (); logoff serviceloaders = thread. getLooper (); serviceHandler = new ServiceHandler (serviceloader) ;}@ Overridepublic void onStart (Intent intent, int startId) {Message msg = serviceHandler. obtainMessage (); msg. arg1 = startId; msg. obj = intent; serviceHandler. sendMessage (msg);} protected void onHandleIntent (Intent intent) {// do your asynchronous task }}


 




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.