29amp;30认识UI Thread.doc
文本预览下载声明
上课讲义摘录之29/30: 认识UI Thread(1/2)
在前面的三篇讲义摘录里:
第1篇— Android的Message Queue(1/3)
第2篇— Android的Message Queue(2/3)
第3篇— Android的Message Queue(3/3)
介绍过Android主线程与子线程之沟通。所谓主线程通常是UI线程。Android的UI是单线程(Single-threaded)的。为了避免拖住GUI,一些较费时的对象应该交给独立的线程去执行。如果幕后的线程来执行UI对象,Android就会发出错误讯息
CalledFromWrongThreadException
例如下述范例:
//----- Looper_05范例 -----
package com.misoo.kx04;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ac01 extends Activity implements OnClickListener {
private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
private final int FP = LinearLayout.LayoutParams.FILL_PARENT;
public TextView tv;
private myThread t;
private Button btn, btn2;
private Handler h;
private Context ctx;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
ctx = this;
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
btn = new Button(this);
btn.setId(101);
btn.setBackgroundResource(R.drawable.heart);
btn.setText(test looper);
btn.setOnClickListener(this);
LinearLayout.LayoutParams param =
new LinearLayout.LayoutParams(100,50);
param.topMargin = 10;
layout.addView(btn, param);
btn2 = new Button(this);
btn2.setId(102);
btn2.setBackgroundResource(R.drawable.ok_blue);
btn2.setText(exit);
btn2.setOnClickListener(this);
layout.addView(btn2,
显示全部