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.
When the user clicks on a button, if the execution is a time-consuming operation, the bad treatment will cause the system to feign death, the user experience is poor, and Android is further, if any one of the acitivity did not respond more than 5 seconds will be forced to shut down, So we need to start another thread to handle the long time-consuming operation, and the main thread is not affected by it, sending a message to the main thread at the end of the time-consuming operation, and then processing the main thread accordingly. It is handler for message passing and asynchronous processing between threads.
The following simulates a simple photo album viewer that automatically changes the next photo every 2 seconds.
Main.xml Layout file
<?XML version="1.0"encoding="Utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
Android:orientation="Vertical"
Android:layout_width="fill_parent"
Android:layout_height="fill_parent"
Android:gravity="Center">
<ImageView Android:id="@+id/imageview"
Android:layout_width="fill_parent"
Android:layout_height="wrap_content"
ANDROID:SRC="@drawable/P1"
Android:gravity="Center"/>
</LinearLayout>
Handleactivity class
PackageCom.ljq.handle;
Importandroid.app.Activity;
ImportAndroid.os.Bundle;
ImportAndroid.os.Handler;
ImportAndroid.os.Message;
ImportAndroid.widget.ImageView;
PublicclasshandleactivityextendsActivity {
PrivateImageView ImageView=NULL;
PrivateHandler Handler=NewHandler () {
@Override
Publicvoidhandlemessage (Message msg) {
Switch(msg.what) {
Case0:
Imageview.setimageresource (R.DRAWABLE.P1);
Break;
Case1:
Imageview.setimageresource (R.DRAWABLE.P2);
Break;
Case2:
Imageview.setimageresource (R.DRAWABLE.P3);
Break;
Case3:
Imageview.setimageresource (R.DRAWABLE.P4);
Break;
}
Super. Handlemessage (msg);
}
};
@Override
PublicvoidonCreate (Bundle savedinstancestate) {
Super. OnCreate (savedinstancestate);
Setcontentview (R.layout.main);
ImageView=(ImageView) Findviewbyid (R.id.imageview);
Thread.Start ();
}
int What=0;
Thread Thread=NewThread (NewRunnable () {
PublicvoidRun () {
while (true) {
Handler.sendemptymessage ( what++) %4);
Try {
Thread.Sleep ( -);
} Catch(Interruptedexception e) {
E.printstacktrace ();
}
}
}
});
}
Run results