我有一個Android應用程序,我只是試驗的東西,我似乎無法弄清楚爲什麼我的應用程序的力量關閉時,我通過一個while循環更新TextView。當我註釋掉updateText方法時,它運行良好。爲什麼當我在更新方法中設置文本時,我的應用程序強制關閉?
public class GameThread extends Thread {
Thread t;
private int i;
private boolean running;
private long sleepTime;
GameView gv;
public GameThread() {
t = new Thread(this);
t.start();
i = 0;
sleepTime = 1000;
}
public void initView(GameView v) {
this.gv = v;
}
public void setRunning(boolean b) {
this.running = b;
}
public boolean getRunning() {
return running;
}
public void run() {
while(running) {
i++;
update();
try {
t.sleep(sleepTime);
} catch(InterruptedException e) {
}
}
}
public void update() {
gv.setText(i); // when this is uncommented, it causes force close
Log.v("Semajhan", "i = " + i);
}
public class GameView extends LinearLayout {
public TextView tv;
public GameView(Context c) {
super(c);
this.setBackgroundColor(Color.WHITE);
tv = new TextView(c);
tv.setTextColor(Color.BLACK);
tv.setTextSize(20);
this.addView(tv);
}
public void setText(int i) {
tv.setText("i count: " + i);
}
public class Exp extends Activity {
GameThread t;
GameView v;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
v = new GameView(this);
setContentView(v);
t = new GameThread();
t.setRunning(true);
t.initView(v);
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (t.getRunning() == true) {
t.setRunning(false);
Log.v("Semajhan", "STOPPED");
} else {
t.setRunning(true);
Log.v("Semajhan", "RESTART");
}
}
return true;
}
protected void onDestroy() {
Log.v("Semajhan", "DESTROYING");
super.onDestroy();
}
protected void onStop() {
Log.v("Semajhan", "Stopping");
super.onStop();
}
我以爲我會發布整個應用程序,因爲它是相對較小,這樣我就可以得到不混亂一些幫助。
因此,爲了長期利益,我應該使用處理程序還是不使用? – semajhan 2010-11-13 22:22:40
其實是的,我編輯了我的答案 – apps 2010-11-13 22:47:45
就像你所說的那樣,但現在我有一件事。我創建了一個帶有活動和擴展線程類的簡單應用程序。現在我在我的活動和線程的一個實例中創建一個處理程序並啓動它。我的活動中還有一個按鈕,用於啓動線程,該線程更新按鈕的文本。這裏是我卡住的地方。我應該如何連接處理程序?我添加了Message.obtain(handler).sendToTarget();在我的線程類,但它說處理程序不能解析爲變量。 – semajhan 2010-12-10 19:41:19