我们正在尝试构建一个应用程序,每隔几秒左右记录一次分贝级别。问题是我们需要在轮询分贝级别的 run() 方法中有一个无限循环,但是当我们添加无限循环时,它会挂起。谁能指出我们正确的方向?谢谢。
代码如下:
package tpsip.tpsip;
import android.app.Activity;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;
public class tpsip extends Activity implements Runnable{
private TextView decibelMeter;
private TextView timeRemaining;
private Button button;
private int safetyTime;
ExposureCalculator calculator = new ExposureCalculator();
Handler handler = new Handler();
Thread thread = new Thread();
LogicLayer logicLayer = new LogicLayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
this.safetyTime = 28800; //8 hours of safe time when the decibel level is between 90-92, levels below this are not considered dangerous to hearing
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.decibelMeter = (TextView)findViewById(R.id.textView2);
this.decibelMeter.setText("0 dB");
this.timeRemaining = (TextView)findViewById(R.id.textView3);
this.timeRemaining.setText("Safety time remaining " + safetyTime + " seconds");
this.button = (Button) findViewById(R.id.button1);
button.setBackgroundColor(Color.GREEN);
button.setText("Ear protection not needed");
handler.post(thread);
this.run();
}
@Override
public void run() {
int a = 10;
while(true) {
this.decibelMeter.setText("0safsafsafa dB");
if (a == Math.random() * 100) break;
}
}
}
最佳答案
在不同的线程上运行操作,并在需要时使用处理程序或 runOnUIThread()
更改 UI。目前,该方法作为常规方法被调用,并在无限循环中运行,这不会让您的 UI 更新。
关于java - 无限循环卡在 run() - 方法(Android 模拟器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5597638/