2011-04-08 41 views
1

我們正試圖建立一個應用程序,每秒鐘左右記錄分貝級別。問題是我們需要在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; 
    } 
} 
} 
+0

見[處理程序(http://developer.android.com/reference/android/os/Handler.html#post%28java.lang.Runnable%29)。 runnable將在該處理程序所連接的線程上運行。 – 2011-04-08 15:59:23

回答

1

運行在不同的線程的opertaion並從那裏使用處理器或runOnUIThread()需要時更改UI。目前該方法被稱爲regullar方法,並在無限循環中運行,不會讓您的UI更新。

1

你在UI線程中運行無限循環嗎?這是你絕對不能做的事情。應用程序將變得無響應和「掛起」,因爲它不能再從操作系統獲取消息。使用另一個線程來運行循環。

最簡單的方法是添加一個延伸Thread的類,並將「run」方法放在那裏。但是,請記住,您無法從另一個線程訪問UI。