0
我想知道如何使AsyncTask倖存screenOrientation更改。所以,我用AsyncTask創建了一個MainActivity的例子。如下面的代碼所示,在 中,doInBackground()方法每秒將變量「i」的增量值打印到7秒,然後使用publishProgress() 發佈變量「i」的值並顯示它在TextView中。而varibale「我」的價值正在發佈我改變了設備的方向,我預計應用程序將崩潰,但是發生了什麼是 ,screenOrientation已更改,變量「i」的值正在發佈並且通常顯示在TextView中而不會崩潰。AsyncTask存活screenOrientation沒有無頭片段
我創建的AsyncTask不是一個適合學習如何在screenOrientation中生存的例子嗎?
MainActivity
public class MainActivity extends AppCompatActivity {
private final static String TAG = MainActivity.class.getSimpleName();
private TextView mtv11Up = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mtv11Up = (TextView) findViewById(R.id.tv11_up);
new ATRetain().execute();
}
private class ATRetain extends AsyncTask<Void, Integer, Void> {
private long mStartTime;
private int i = 0;
@Override
protected void onPreExecute() {
super.onPreExecute();
this.mStartTime = TimeUtils.getTSSec();
}
@Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "started");
while((TimeUtils.getTSSec() - this.mStartTime) <= 7) {
Log.i(TAG, "i: " + (++i));
publishProgress(i);
SystemClock.sleep(1000);
}
Log.i(TAG, "finished");
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mtv11Up.setText(String.valueOf(values[0]));
}
}
}