new Thread() {
public void run() {
try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
while (hasData < 100) {
progressStatus += (int)(Math.random() * 10);
handler.sendEmptyMessage(0x123);
// if (hasData >= 100) { Toast... } // 標註為 Dead Code
}
}
}.start();
new Thread() {
public void run() {
int progress = 0;
while (progress < 100) {
try { Thread.sleep(100); } catch (InterruptedException ignored) {}
progress += new Random().nextInt(10);
if (progress >= 100) progress = 100;
handler.obtainMessage(0x123, progress, 0).sendToTarget();
}
}
}.start();
// 在 Activity/Fragment 中
int progress = 0;
Runnable updater = new Runnable() {
@Override public void run() {
progress += new Random().nextInt(10);
if (progress >= 100) { progress = 100; showDone(); }
else { textView.setText(progress + "%"); handler.postDelayed(this, 100); }
}
};
handler.post(updater);
// Kotlin 協程
lifecycleScope.launch {
var progress = 0
while (progress < 100) {
delay(100)
progress += (1..10).random()
progress = progress.coerceAtMost(100)
_progressLiveData.postValue(progress) // 傳遞給 UI
}
showDone()
}
**Dead Code 警告是編譯器送的禮物,揭示了邏輯漏洞;修好邏輯,警告自然消失。**