The handler implements the function of timing tasks, and the picture is displayed in a carousel every 4 seconds

             We know that the handler has two functions, one is to implement timed tasks, and the other is to implement information communication between the main thread and sub-threads, especially in Android, time-consuming operations cannot be performed in the main thread, and update interface operations cannot be performed in sub-threads. In the context of this demand, the combination of handler+thread appeared to realize the sub-threads read network data, and notify the main thread to update the UI after reading. But what I wrote in this article is the scheduled task function of the handler.

          First of all, we must understand the key method postDelayed(Runnable r, long delaymillis) method in the handler class. The function of this method is to delay delaymillis milliseconds to execute the code of the run method part of the Runnable object once, and write it in a recursive form to execute the run method code of r in an infinite loop. At this time, the runnable does not open a new thread, it is still executed in the thread where the handler is located.

Below is the full code for the small example of the carousel I made, which runs without any issues on my phone.

picture:

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;

public class handlerImage extends Activity {

	ImageView iView;
	Handler myhandler;
	myRun runnable = new myRun();
	int img[] = { R.drawable.a, R.drawable.b, R.drawable.timg };//三张图片
	int i = 1;
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.img);
		iView = (ImageView) findViewById(R.id.imageView1);
		myhandler = new Handler();
		myhandler.postDelayed(runnable, 2000);
	}

	class myRun implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			iView.setImageResource(img[i % 3]);
			i++;
			myhandler.postDelayed(runnable, 4000);//每4000毫秒执行一次run方法
		}
	}
}

Also attach the xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>

   Not long after graduating from university, this is the first time I have contacted the handler again. I don’t know much about it. If there are any mistakes, I hope you will correct me in the comment area.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325828435&siteId=291194637