【发布时间】:2014-09-14 13:28:33
【问题描述】:
我正在尝试创建一个线程,该线程将运行一个 While 循环,并在 while 循环内执行将更改 UI 的操作:
public void GameHandler()
{
layout = (RelativeLayout) findViewById(R.id.MyLayout);
params=new RelativeLayout.LayoutParams(30,40);
btn1 = (Button) findViewById(R.id.MovingObj);
xBounds=new int[2];
yBounds=new int[2];
xBounds[0]=0;
xBounds[1]=layout.getWidth();
yBounds[0]=0; //will change once i set up the screen settings !
yBounds[1]=layout.getHeight();
selectFlyingObject();
Runnable myRunnable = new Runnable() {
@Override
public void run() {
while (CurrentXLocation <= xBounds[1] + 10) {
CurrentXLocation = CurrentXLocation + 1;
params.leftMargin = CurrentXLocation;
params.topMargin = 50;
btn1.setLayoutParams(params);
SystemClock.sleep(1000 - SpeedRate);
}
}
};
Thread myThread = new Thread(myRunnable);
myThread.start();
}
但是我的第一个问题是出现以下错误:
Only the original thread that created a view hierarchy can touch its views.
第二个问题是我听说在后台使用线程会消耗太多的设备 CPU,这可能会导致我的应用程序崩溃。确实会发生这样的事情吗? 谢谢你的回答
【问题讨论】:
-
“我听说在后台使用线程会消耗太多的设备 CPU”。这有点像说“我听说冬天会太冷”。虽然在某些情况下可能是这样,但这取决于很多因素。如果您想避免 ANR 等,最好将繁重的计算放在其他(非 UI)线程中。
-
@Ordous:我建议复制的问题的答案描述了 OP 针对这个问题提出的问题的解决方案(我过去自己使用过的解决方案)。我想说这与这个问题有很大关系。
-
如果我只想更新 android ui 一次,您发布的线程将非常有帮助,但我的线程每 1 秒或更短时间更新一次 ui!如何使用您每秒发布的线程中的信息来更改按钮的坐标???
-
@kasf 在你让你的线程“休眠”后发布它,在循环内..
标签: android multithreading loops user-interface while-loop