Android 消息机制 进程调度问题
“子线程不能更新主线程各个组件的状态。”
下面通过一个自动增长的操作讲解这一点:
定义布局管理器main.xml:
<?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="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
我们首先定义这样Activity程序,通过Timer类完成定时更新:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
//用来更新文本信息
public class MessageDemo extends Activity {
private TextView info = null;
private static int count = 0; //表示更新后的记录
private static final int SET = 1; //操作的what状态
private Handler myHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
info = (TextView) super.findViewById(R.id.info);
Timer timer = new Timer();
timer.schedule(new MyTask(), 0, 1000);
}
private class MyTask extends TimerTask{
@Override
public void run() {
MessageDemo.this.info.setText("消息处理"+ count++); //我们在子线程更新主线程中的count
}
}
}
运行后发现报错。
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
所以我们只能在主线程中更新自身的操作,通过子线程的变化,让主线程修改自身的count++操作。
修改后的Activity程序:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
//用来更新文本信息
public class MessageDemo extends Activity {
private TextView info = null;
private static int count = 0; //表示更新后的记录
private static final int SET = 1; //操作的what状态
private Handler myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case SET:
MessageDemo.this.info.setText("消息处理"+ count++);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
info = (TextView) super.findViewById(R.id.info);
Timer timer = new Timer();
timer.schedule(new MyTask(), 0, 1000);
}
private class MyTask extends TimerTask{
@Override
public void run() {
Message msg = new Message();
msg.what = SET;
MessageDemo.this.myHandler.sendMessage(msg);
}
}
}
运行后可以程序可以正常运行。