Java 无限循环挂起在run()方法中(Android emulator)
我们正在尝试构建一个应用程序,每秒钟左右记录一次分贝级别。问题是在run()方法中需要一个无限循环来轮询分贝级别,但是当我们添加无限循环时,它会挂起。有人能给我们指出正确的方向吗?谢谢 代码如下:Java 无限循环挂起在run()方法中(Android emulator),java,android,android-emulator,Java,Android,Android Emulator,我们正在尝试构建一个应用程序,每秒钟左右记录一次分贝级别。问题是在run()方法中需要一个无限循环来轮询分贝级别,但是当我们添加无限循环时,它会挂起。有人能给我们指出正确的方向吗?谢谢 代码如下: package tpsip.tpsip; import android.app.Activity; import android.graphics.Color; import android.media.AudioManager; import android.media.ToneGenerator
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;
}
}
}
在不同的线程上运行操作,并在需要时使用handler或
runOnUIThread()
从那里更改UI。目前,该方法被称为常规方法,并在无限循环中运行,不允许更新UI。您是否在UI线程中运行无限循环?这是你永远不能做的事。应用程序将变得无响应且“挂起”,因为它无法再从操作系统获取消息。使用另一个线程来运行循环
最简单的方法是添加一个扩展
Thread
的类,并将“run”方法放在那里。但是,请记住,您不能从另一个线程访问UI。正如其他人所说,您不能在主/UI线程上运行长时间运行的操作。您的应用程序被锁定,因为onCreate()永远无法返回并更新UI
请改用AsyncTask:
请参阅。runnable将在该处理程序所连接的线程上运行。