Android: The subthread sends a message to the main UI thread, androidui
In Android, the UI thread cannot be blocked. Therefore, we need to put time-consuming work in the Child thread for processing.
How can I notify the UI thread after the sub-thread takes time to process?
We can create a handler object in the main UI thread and rewrite the handleMessage (Message msg) method, this method will receive the sendMessage (Message msg) of the handler object in the subthread. In this way, the work will be completed at the first delivery;
The content of the message sent from the main thread to the subthread can be viewed in my previous blog, which describes the logoff class and its two important methods and implementation principles.
In Android, when the main UI thread itself has implemented the logoff function, it is very easy for the subthread to send messages to the main thread;
The following is an example. The subthread sends a number every second to the UI main thread. The UI main thread displays the number on its TextView control.
Well, let's take a look at the run:
The following code is attached:
MainActivity. java:
package activity.wyc.com.threaddemo;import android.os.Handler;import android.os.Message;import android.os.SystemClock;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;public class MainActivity extends ActionBarActivity { private TextView tvObj; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvObj = (TextView) findViewById(R.id.tvid); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); tvObj.setText(String.valueOf(msg.arg1)); } }; new Thread(new Runnable() { @Override public void run() { int num = 0; while (true) { Message message = Message.obtain(); message.arg1 = num; handler.sendMessage(message); SystemClock.sleep(1000); num = ++num; } } }).start(); }}
Activity_main.xml:
<LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:gravity="center_horizontal" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/tvid" android:textSize="40sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /></LinearLayout>
The following is the source code (written by Baidu cloud disk and Android studio ):
Http://pan.baidu.com/s/1kT9oKbP