私はスレッド化を理解しようとしていますが、アプリがバックに送信されてから復元されると、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();
}
}