我們正試圖建立一個應用程序,每秒鐘左右記錄分貝級別。問題是我們需要在run()方法中有一個無限循環來輪詢分貝級別,但是當我們添加無限循環時,它會掛起。任何人都可以將我們指向正確的方向嗎?謝謝。無限循環掛在運行() - 方法(Android模擬器)
下面的代碼:
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;
}
}
}
見[處理程序(http://developer.android.com/reference/android/os/Handler.html#post%28java.lang.Runnable%29)。 runnable將在該處理程序所連接的線程上運行。 – 2011-04-08 15:59:23