3
atm我的实际Android应用程序出现问题。在Android中连续运行Handler任务
对于解释:
起初,我想表现出一个TextView字符由字符文本。这是我为这个
tvIntro.setText("");
final Handler textHandler = new Handler();
for(int i=0; i<intro.length();i++){
final int finalCount = i;
textHandler.postDelayed(new Runnable() {
@Override
public void run() {
tvIntro.setText(tvIntro.getText() + (intro.charAt(finalCount)+""));
}
}, 150 * i);
}
实际的代码显示整个文本后,我想打一个声音不断改变屏幕的颜色为5秒。对于这一点,我的代码是:
myBackground.setBackgroundColor(Color.RED);// set initial colour
final Thread blink = new Thread(new Runnable() {
public void run() {
while (getRunning()) {
try {
Thread.sleep(100);
if(start[0] !=1){
mp.start();
start[0] = 1;
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
updateColor(myBackground);
whichColor = !whichColor;
}
}
});
private void updateColor(final RelativeLayout myBackground) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (whichColor)
myBackground.setBackgroundColor(Color.RED);
else
myBackground.setBackgroundColor(Color.GREEN);
}
});
}
所有功能都工作,但我想也完成了第一个处理程序,执行第二处理程序之前。此外,第二个处理程序应该在x秒后停止。
我对理解处理程序和线程是如何工作有些问题。 如果你的某个人为我解决问题,那该多好。
如果你想完成一个处理程序,设置为null,例如:“textHandler = null;”,否则它将一直存在,直到它的活动完成。 –