asyncTask の使用方法を学習していますが、TextView をリアルタイムで表示しようとすると問題が発生します。mainActivity には、新しいアクティビティを開始するいくつかのボタンと、200 ミリ秒ごとに変化する値を示す TextView があります。しかし、問題は、ボタンをクリックして別のアクティビティを開始するまで TextView が表示されず、「戻るボタン」を押して mainActivity に戻っても値が変わらないことです。ただし、ボタンを押して別のアクティビティを開始すると、値が変更されます。
private TextView t;
private int counter;
private boolean isUiVisible = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.counter);
counter = 0;
}
@Override
public void onStart(){
super.onStart();
isUiVisible = true;
new UpdateUi().execute();
}
@Override
public void onPause(){
super.onPause();
isUiVisible = false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class UpdateUi extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
while (true) {
if (isUiVisible) {
counter++;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
// Ensure the asynkTask ends when the activity ends
break;
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
t.setText(counter + "");
}
}
public void callRed(View view){
Intent intent = new Intent(this, RedActivity.class);
startActivity(intent);
}
public void callYellow(View view){
Intent intent = new Intent(this, YellowActivity.class);
startActivity(intent);
}
onProgressUpdate で setText を試しましたが、何も表示されませんでした。他に問題があるかどうかも検索しましたが、私のものと同じ問題があるようです (1 つは onClickListener で、これは私が探していたものではありませんでした)。