此代碼在旋轉屏幕時不起作用。 我嘗試使用處理程序,但消息與先前的活動(在旋轉之前)和新的活動分離。從AsyncTask更新UI並正確處理屏幕旋轉
¿線程如何將消息發送到新的活動? 請不要建議避免旋轉屏幕。
public class SampleActivity extends Activity {
TextView text;
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
text = new TextView(this);
text.setText("HELLO");
layout.addView(text);
if (savedInstanceState != null) {
text.setText(savedInstanceState.getString("text"));
}
setContentView(layout);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("text", text.getText().toString());
}
@Override
protected void onStart() {
super.onStart();
new CounterTask().execute();
}
public class CounterTask extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... params) {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
publishProgress("Hello " + i);
} catch (Exception e) {
}
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
String str = values[0];
text.setText(str);
}
}
}