我是安卓系统的新手。我在安卓开发者网站上看到了关于安卓线程的两条规则:
1 : Do not block the UI thread
2 : Do not access the Android UI toolkit from outside the UI thread
如果你查看android sdk的LunarLander示例,你可以看到以下代码:
class LunarView extends SurfaceView implements SurfaceHolder.Callback {
//...
public LunarView(Context context, AttributeSet attrs) {
class LunarThread extends Thread {
//...
private void doDraw(Canvas canvas) {
//do some drawing on the canvas
}
}
//...
public LunarView(Context context, AttributeSet attrs) {
super(context, attrs);
// ...
// create thread only; it's started in surfaceCreated()
thread = new LunarThread(holder, context, new Handler() {
@Override
public void handleMessage(Message m) {
mStatusText.setVisibility(m.getData().getInt("viz"));
mStatusText.setText(m.getData().getString("text"));
}
});
//...
}
//...
}
正如您所看到的,我们正在创建一个新的线程来渲染视图。
为什么这个代码没有违反android框架线程的第二条规则?
感谢阅读。
我以前从未尝试过此代码。但我猜handleMessage(Message m)
是在主(UI)线程中执行的。为了验证它,您可以添加一些代码进行检查。
thread = new LunarThread(holder, context, new Handler() {
@Override
public void handleMessage(Message m) {
if (Thread.currentThread().getId() == 1) {
// main thread
}
else {
// other thread
}
mStatusText.setVisibility(m.getData().getInt("viz"));
mStatusText.setText(m.getData().getString("text"));
}
});
线程没有呈现视图。我不完全确定它是如何工作的,但它使用处理程序向拥有视图的线程发送消息。LunarLander以与本例相同的方式管理线程:https://developer.android.com/training/multiple-threads/communicate-ui.html