Android thread processing: Handler summary, android thread handler
The previous article introduced how to send Message data to the main thread through the Handler object, in this article, I will take an example to summarize the use of Handler. The example is to use Handler to achieve the effect of automatic image changes. Generally, we use Viewpage to achieve this effect, however, let's take a look at how to achieve this through Handler.
Before we start, we need to prepare several images for update and switch, so that we can put these images under drawable-hdpi under res. With these, we can start to achieve our results:
1. layout file:
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" tools: context = "$ {relativePackage }. $ {activityClass} "> <ImageView android: id =" @ + id/imageView1 "android: layout_width =" 300px "android: layout_height =" 300px "android: layout_alignParentTop = "true" android: layout_centerHorizontal = "true" android: layout_marginTop = "87dp" android: src = "@ drawable/abc_ AB _pai_pack_holo_light"/> <Button android: id = "@ + id/stop" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignLeft = "@ + id/imgButton" android: layout_alignParentTop = "true" android: layout_marginTop = "36dp" android: text = "Stop switching"/> </RelativeLayout>
2. Our Activity code:
Public class ImgActivity extends Activity {private ImageView imageView; private Button stop; private Handler handler = new Handler (); private int ImageAll [] = {R. drawable. download1, R. drawable. download2, R. drawable. download3}; private int index = 1; private MyRunable myRunable = new MyRunable (); @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_img); stop = (Button) findViewById (R. id. stop); imageView = (ImageView) findViewById (R. id. imageView1); stop. setOnClickListener (new OnClickListener () {@ Override public void onClick (View arg0) {handler. removeCallbacks (myRunable); // stop switching}); handler. postDelayed (myRunable, 1000);} class MyRunable implements Runnable {@ Override public void run () {index = index % 3; imageView. setImageResource (ImageAll [index]); index ++; handler. postDelayed (myRunable, 1000 );}}}
Now our instance is complete. Let's briefly introduce the Code:
Index = index % 3;: controls our image Switching
Handler. postDelayed (myRunable, 1000);: Execute our myRunable object every 1 s
Handler. removeCallbacks (myRunable);: remove our myRunable object and stop the execution.
OK. We have already completed the introduction of the Instance effect. You can write it on your own. It is very interesting!