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