搞安卓开发的初学者由于对java线程的轻车熟路往往导致在安卓线程开发上遇到困难,主要原因是安卓是从总体上看是一个单线程的UI操作流程,因此安卓所有的view、控件都要在UI线程(主线程)上进行创建、修改、移除。不多说直接还是那个代码了。。。。
package com.icedcap.handlertest;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button button;
private TextView tv;
private Handler handler;
private int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
handler = new MyHandler();
}
private void init() {
button = (Button) findViewById(R.id.button);
tv = (TextView) findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 启动第二线程
new MyThread().start();
}
});
}
class MyThread extends Thread {
@Override
public void run() {
try {
System.out.println("MyThreadName--->"
+ Thread.currentThread().getName());
Thread.sleep(500);
Message msg = handler.obtainMessage();
count++;
msg.obj = count;
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
System.out.println("MyHandlerName--->"
+ Thread.currentThread().getName());
int n = (Integer) msg.obj;
tv.setText("点击了" + n + "下!");
}
}
}
布局文件很简单
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textview"
android:text="点击按钮更新textview" />
</RelativeLayout>
补充:若想在不同的类里执行后台线程并将结果反馈给主线程交由主线程来更新界面,那么必须在主线程中声明一个全局的handler对象,并且在启动Activity时初始化handler,调用后台线程时将该handler传过去。
源码下载地址:
本文详细解析了在Android开发中如何在UI线程与后台线程间进行有效交互,通过实例展示了如何在不同类中执行后台线程任务并将其结果反馈给UI线程进行界面更新。
3328

被折叠的 条评论
为什么被折叠?



