我對Java編程非常陌生,並且遇到線程中while循環的麻煩。我在這裏發佈一個我使用while循環的例子。應用程序與線程崩潰
public class MainActivity extends AppCompatActivity {
private boolean running = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView)findViewById(R.id.textView);
new Thread(new Runnable() {
@Override
public void run() {
while (running) {
try{Thread.sleep(1000);}
catch(InterruptedException e){}
running = false;
text.setText("false!");
running = true;
try{Thread.sleep(1000);}
catch(InterruptedException e){}
text.setText("True!");
}
}
}).start();
}
}
當運行設置爲false時,線程不會運行,應用程序不會顯示任何內容。當運行設置爲true時,應用程序崩潰後 text.setText(「false!」);
謝謝大家提前!
閱讀異常消息(並將其發佈到您的問題中)。它應該告訴你,你不能更新UI線程之外的用戶界面 – AxelH
看看logcat併發布堆棧跟蹤 – Jens
這個[answer](http://stackoverflow.com/a/5185140/4391450)是最簡單的使用 – AxelH