標籤:.net over append 先來 csdn textview hid 編寫 val
在Android裡,UI線程是不同意被堵塞的。因此我們要將耗時的工作放到子線程中去處理。
那麼子線程耗時處理後要如何通知UI線程呢?
我們能夠在UI主線程中建立一個handler對象,然後通過重寫其handleMessage(Message msg)的方法,該方法會接收到子線程中的handler對象的sendMessage((Message msg)發回來的訊息。這樣一發一收就完畢工作。
而關於主線程向子線程發送訊息的內容能夠看我的上一篇部落格。當中講到了Looper類及其兩個重要方法和實現原理。
在Android中當UI主線程本身已實現了Looper的功能。所以不用我們擔心。所以子線程向主線程發送訊息是很easy的。
以下寫個範例。子線程每秒鐘會向UI主線程發送一個數字。UI主線程會將該數字顯示在自己的TextView控制項上。
好那麼先來看一下執行吧:
以下附上代碼:
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>
以下是原始碼(百度雲端硬碟。Android studio編寫):
http://pan.baidu.com/s/1kT9oKbP
Android:子線程向UI主線程發送訊息