我试图找出线程并遇到这个问题,如果应用程序被发送到后面,TextView 会停止更新,然后再恢复。
如何确保应用程序重新回到前面后 TextView 继续更新?
或者...
重新启动活动后,如何将 TextView 重新连接到我的可运行线程中的处理程序?
有一个进度条可以正常工作,所以我有点困惑。我很感激一些建议,因为我认为我可能犯了一个简单的错误。
public class ThreadTestActivity extends Activity {
private Handler handler;
private static ProgressBar progress;
private TextView tv;
private int counter = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ThreadTest);
handler = new Handler();
progress = (ProgressBar) findViewById(R.id.progressBar1);
tv = (TextView) findViewById(R.id.myText);
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
thread_fun();
});}
}
private void thread_fun() {
new Thread(new Runnable() {
public void run() {
try {
while (counter < 100) {
counter += 20;
Thread.sleep(2000);
// Update the progress bar and TextView (in 5 chunks of 20, 0 to 100)
// This works perfectly it the app stays in front
handler.post(new Runnable() {
public void run() {
// but after sending to the back (esc) and bringing the activity back to the front
progress.setProgress(counter); //This progres bar maintains its value and updates correctly
tv.setText(String.valueOf(counter)); //This TextView reverts to its default text and does not update
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}