Ext: Creation and destruction of Android threads

Source: Internet
Author: User

http://mt.sohu.com/20140813/n403395303.shtml?recsyssohu=2

Threads are often used in Android development, and many students immediately use the new thread () {...} When thinking about threads. Start () in this way. This way, if the above code is called multiple times in an activity, multiple anonymous threads are created, and the longer the program runs, the slower it may become. Therefore, a handler is required to start a thread, and a thread is removed to ensure that the thread is not created repeatedly.

1, the general way to create handler
Typically use handler handler = new handler () {...} Create. This creates a handler that is handler under the main thread, the UI thread, which is bound to the default looper under the UI thread. The looper is used to implement Message Queuing and message loop mechanisms.
Therefore, if the handler is created by default then it is not possible to create a handler if the thread is doing some time-consuming operations such as network fetch data.

2. Using Handlerthread
Handlerthread is actually a thread, but it's a looper more than a normal thread. We can use the following example to create a handler
Handlerthread thread = new Handlerthread ("Myhandlerthread");
Thread.Start ();
Mhandler = new Handler (Thread.getlooper ());
Mhandler.post (mbackgroundrunnable);
The start () method is called when the Handlerthread is created. The Looper object in Handlerthread is then passed in when the handler is created. Then the Mhandler object is bound to the Handlerthread thread (which is no longer tied to the UI thread, so it does not block the UI when it handles the time-consuming operation).
Finally, the thread that implements the time-consuming operation is post to the Mhandler message queue. Note that the mbackgroundrunnable thread does not start because there is no call to the start () method.

3, the complete Angrycode
public class Mainactivity extends Activity implements onclicklistener{
public static final String TAG = "mainactivity";

Private Handler Mhandler;

Private Boolean mrunning = false;

Private Button mBtn;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Handlerthread thread = new Handlerthread ("Myhandlerthread");
Thread.Start ();//Create a handlerthread and start it
Mhandler = new Handler (Thread.getlooper ());//Looper using Handlerthread Handler object, if using the default construction method, it is likely to block the UI thread
Mhandler.post (mbackgroundrunnable);//post a thread to handler

MBtn = (Button) Findviewbyid (R.id.button);
Mbtn.setonclicklistener (this);
}
@Override
protected void Onresume () {
Super.onresume ();
Mrunning = true;
}
@Override
protected void OnStop () {
Super.onstop ();
Mrunning = false;
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}
Threads that implement time-consuming operations
Runnable mbackgroundrunnable = new Runnable () {

@Override
public void Run () {
----------simulate time-consuming operations and start---------------
while (mrunning) {

LOG.I (TAG, "thread running!");

try {
Thread.Sleep (200);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
----------simulate time-consuming operations and end---------------
}
};
@Override
protected void OnDestroy () {
Super.ondestroy ();
Destroying threads
Mhandler.removecallbacks (mbackgroundrunnable);

}
@Override
public void OnClick (View v) {
Toast.maketext (Getapplication (), "click the button!!!", Toast.length_short). Show ();
}
}
In the above Angrycode, handler will block the UI thread if you create mbackgroundrunnable in the OnCreate () method instead of using Handlerthread in the default constructor of handler.

4. Thread Destruction
Use the above method to create a thread that can be used when destroying
Mhandler.removecallbacks (mbackgroundrunnable);
Destroy a thread so that you can avoid creating multiple threads that are running concurrently when you enter the same activity multiple times.

Ext: Creation and destruction of Android threads

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.