我有以下课程。该课程的目的是让我通过每秒显示大约十个字符来模拟电传打字机/打字机。
CharacterLoopThread 类的重点是查看 outputBuffer,如果其中有任何字符,则在 UI 线程上调用一个可运行的对象,该线程会提取第一个字符并将其放入 textView。然后线程休眠大约 100 毫秒。(这里有一些恶作剧……虽然电传打字机在我 1979 年使用的时候很棒,但现在我的口味有点慢。所以每 10 个字符,我稍微减少延迟。当没有更多字符可以显示时,我将延迟重置为 100 毫秒...)
我编辑了课程的底部,因为它与我的问题无关。
我在这里所拥有的似乎运作良好。然而,它是因为我还是不管我?您首选的编写线程和处理程序的方式是什么?
public class MyActivity extends Activity {
private TextView textView;
private ScrollView scrollView;
private StringBuilder outputBuffer;
private Handler handler;
private CharacterLooperThread characterLooperThread;
(剪断)
private class CharacterLooperThread extends Thread {
private boolean allowRun;
private Runnable run;
int effectiveCharacterDelay;
int characterCount;
public CharacterLooperThread() {
allowRun = true;
run = new Runnable() {
public void run() {
/**
* Don't do anything if the string has been consumed. This is necessary since when the delay
* is very small it is possible for a runnable to be queued before the previous runnable has
* consumed the final character from the outputBuffer. The 2nd runnable will cause an
* exception on the substring() below.
*/
if (outputBuffer.length() == 0) return;
try {
textView.append(outputBuffer.substring(0, 1));
scrollToBottom();
outputBuffer.deleteCharAt(0);
} catch (Exception e) {
toast(getMsg(e));
}
}
};
}
public void run() {
resetDelay();
while (allowRun) {
/**
* This if() performs 2 functions:
* 1. It prevents us from queuing useless runnables in the handler. Why use the resources if
* there's nothing to display?
* 2. It allows us to reset the delay values. If the outputBuffer is depleted we can reset the
* delay to the starting value.
*/
if (outputBuffer.length() > 0) {
handler.post(run);
reduceDelay();
} else {
resetDelay();
}
try {
Thread.sleep(effectiveCharacterDelay);
} catch (InterruptedException e) {
toast("sleep() failed with " + e.getMessage());
}
}
/**
* Make sure there's no runnable on the queue when the thread exits.
*/
handler.removeCallbacks(run);
}
public void exit() {
allowRun = false;
}