If we directly put the processing function in OnCreate or OnStart of Activity when processing download or other tasks that require long execution, the entire Activity will not respond during execution, if the time is too long, the program will be suspended. Handler puts these functions in a separate thread for execution, which is independent from Activity.
When you click a button, If you perform a time-consuming operation, poor processing will lead to a system crash and poor user experience, while Android goes further, if any Acitivity does not respond for more than five seconds, it will be forcibly disabled. Therefore, we need to start another thread to handle long-time operations, and the main thread will not be affected, after a time-consuming operation is completed, the message is sent to the main thread, and the main thread then processes the message accordingly. Handler is used for message transmission and asynchronous processing between threads.
The following simulates a simple album viewer, which automatically replaces 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
package com.ljq.handle;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
public class HandleActivity extends Activity {
private ImageView imageView = null;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
imageView.setImageResource(R.drawable.p1);
break;
case 1:
imageView.setImageResource(R.drawable.p2);
break;
case 2:
imageView.setImageResource(R.drawable.p3);
break;
case 3:
imageView.setImageResource(R.drawable.p4);
break;
}
super.handleMessage(msg);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.imageView);
thread.start();
}
int what = 0;
Thread thread = new Thread(new Runnable() {
public void run() {
while (true) {
handler.sendEmptyMessage((what++) % 4);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
Running result