Use of handler in Android

Source: Internet
Author: User

When we are dealing with downloads or other tasks that need to be performed for a long time, if you put the handler function directly in the activity's OnCreate or onstart, it will cause the entire activity to be unresponsive during execution, and if the time is too long, the program will hang. handler is the ability to put these functions into a separate thread to execute, and not affect the activity.

Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;

 Public classHandleactivityextendsActivity {PrivateImageView ImageView =NULL; PrivateHandler Handler =NewHandler () {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Case0:
Your Operation Break; Case1:
Your affectation. Break; } Super. Handlemessage (msg);} }; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r.layout.main);Thread.Start ();}Thread Thread=NewThread (NewRunnable () { Public voidRun () {Message message = new Message ();

Message.what = 1;
Message.obj = obj;

Handler.sendmessage (message);

 } });}


Can also be written directly within a method to implement

private void Getrealtimebills (final String date)
{
Final Handler Handler = new Handler ()

{
@Override
public void Handlemessage (Message msg)

{
if (msg.what = = 1)
{
Realtimebills = (realtimebills) msg.obj;
}
}
};
New Thread () {
@Override
public void Run ()

{
Message message = new Message ();
Try

{
Realtimebills = context.getrealtimebills (date);
if (Realtimebills.getresultmessage (). OK ())
{
Message.what = 1;
Message.obj = Realtimebills;
}

catch (Exception e)

{
E.printstacktrace ();
}
Handler.sendmessage (message);
}
}.start ();
}

Use of handler in Android

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.