[英]Thread.sleep causes android program to crash
我正在嘗試制作一個監控網絡連接的程序,一個顯示狀態和帶寬並每秒刷新一次的程序。 昨天我了解到網絡監控發生在我創建的輔助線程上; 它現在有效。
我相信讓程序每秒刷新一次,我做一個while循環,其中while條件總是“true”,而在while循環結束時我“嘗試”一個Thread.sleep(1000)。
我有一個問題和一個問題。
問題:我是否冒着充斥我的計划的風險? 我覺得通過設置secondaryThread = null,在while循環期間創建的所有數據都會被垃圾收集,但我不確定是否是這種情況。
問題:當我運行這個時,我收到一條消息“[程序]意外退出”......讓我覺得我確實充斥了程序。 有辦法解決這個問題嗎?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int linkSpeed = -1;
TextView textView = new TextView(this);
while (true)
{
SecondaryThread secondaryThread = new SecondaryThread(this);
new Thread(secondaryThread).start();
linkSpeed = secondaryThread.getLinkSpeed();
secondaryThread = null;
// Create the text view
textView.setTextSize(25);
textView.setText("linkspeed = " + linkSpeed);
// Set the text view as the activity layout
setContentView(textView);
try {
Thread.sleep(1000);
}
catch (Exception e) {
textView.setTextSize(25);
textView.setText("oh shit");
}
}
LogCat跟蹤堆棧表示一切正常,即使這不是實際情況。 具體來說,它說以下......
06-27 15:07:58.069: D/gralloc_goldfish(1312): Emulator without GPU emulation detected.
06-27 15:41:45.879: I/dalvikvm(1919): threadid=3: reacting to signal 3
06-27 15:41:45.958: I/dalvikvm(1919): Wrote stack traces to '/data/anr/traces.txt'
你永遠不想在UI Thread
上調用Thread.sleep()
,它看起來就像你在這里做的那樣。 您可以將它放在您創建的Thread
,並使用runOnUiThread()
來更新TextView
永遠不要阻止UI線程。 使用后台線程:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TextView textView = new TextView(this);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
int globalState = 1;
while (true) {
// <cut>
// Create the text view
// new scope
{
final int linkSpeed = ++globalState;
textView.post(new Runnable() {
@Override
public void run() {
textView.setTextSize(25);
textView.setText("linkspeed = " + linkSpeed);
// Set the text view as the activity layout
setContentView(textView);
}
});
}
try {
Thread.sleep(1000);
} catch (Exception e) {
textView.post(new Runnable() {
@Override
public void run() {
textView.setTextSize(25);
textView.setText("oh XXXX");
}
});
}
}
}
}.execute();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.