[Android] message mechanism

1. Message
message, understood as a data unit communication between threads. For example, a background thread after the completion of processing of data need to be updated UI, you can send a Message containing the updated information to the UI thread.
Handler 2.
Handler Message is the main handler, responsible for adding Message to the message queue and message queue Message for processing.
3. Looper
circulator acts as a bridge between the Message Queue Handler and, circulating inside the Message Message Queue removed, processed and delivered to the appropriate Handler.

Refer to the following Example:
.xml code is as follows:

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

.java code is as follows:

package org.lxh.demo;
 
import java.util.Timer;
import java.util.TimerTask;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class Hello extends Activity {
	public static int count = 1;
	public static final int SET = 1;
	private TextView msg = null;
	private Handler myHandle = new Handler() {
 
		@Override
		public void handleMessage(Message msg) {//覆写此方法
			switch (msg.what) {//判断操作类型
			case SET:
				Hello.this.msg.setText("MLDN-" + count++);
			}
		}
 
	};
 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); // 生命周期方法
		super.setContentView(R.layout.main); // 设置要使用的布局管理器
		this.msg = (TextView) super.findViewById(R.id.info);
		Timer timer = new Timer();//定义调度器
		timer.schedule(new MyTask(), 0, 1000);//0表示立即开始,1000表示间隔为一秒
 
	}
 
	private class MyTask extends TimerTask {
 
		@Override
		public void run() {//启动线程
			Message msg = new Message();
			msg.what = SET;
			Hello.this.myHandle.sendMessage(msg);
 
		}
 
	}
}

Here Insert Picture Description

Published 73 original articles · won praise 17 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_40110781/article/details/104942670