我有一个方法可以让 TextView 充当“正在加载...”指示器。
我正在使用每 .5 秒更新一次 TextView 的 Runnable 来执行此操作。这是我的功能:
public void displayFlash() {
animate = true;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
while(animate) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
public void run() {
System.out.println("Running");
numFrames++;
switch (numFrames % 3) {
case 0:
loading.setText("Loading.");
break;
case 1:
loading.setText("Loading..");
break;
case 2:
loading.setText("Loading...");
break;
}
}
});
}
}
};
new Thread(runnable).start();
}
问题是,在这个 Activity 完成(并销毁)之后,线程继续运行。我在 Runnable 中有一个 System.out.println("running");
并在此 Activity 完成后继续记录。我需要做什么才能杀死它?我已经尝试过 handler.removeCallbacks(runnable);
和 Thread.interrupt();
但没有成功。
最佳答案
public void displayFlash() {
animate = true;
final Handler handler = new Handler();
Runnable yourRunnable = new Runnable() {
@Override
public void run() {
System.out.println("Running");
numFrames++;
switch (numFrames % 3) {
case 0:
loading.setText("Loading.");
break;
case 1:
loading.setText("Loading..");
break;
case 2:
loading.setText("Loading...");
break;
}
handler.postDelayed(this, 500);
}
}
handler.post(yourRunnable);
}
完成后,调用 handler.removeCallbacks(yourRunnable);
关于java - Activity 结束后停止 Handler Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31844281/