我写了一个简单的测试来查看AsyncTask
保留的生命周期Fragment
。它可以确认@Alex Lockwood 的回答是正确的。所以可以肯定地说AsyncTask
in a reservedFragment
是最佳实践。而谷歌应该将这种方法写入他们的官方文件中。
public class RecordDataFragment extends Fragment {
public static boolean detach = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Timber.d("retain, onAttach");
detach = false;
}
@Override
public void onDetach() {
super.onDetach();
Timber.d("retain, onDetach");
detach = true;
}
public static class TestTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... username) {
Timber.d("retain, looping.");
while(!detach){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Timber.d("retain, exit looping.");
return null;
}
protected void onPostExecute(Void nothing) {
Timber.d("retain, onPostExecute");
}
}
}
public class RecordFragment extends Fragment {
static boolean called = false;
@Override
public void onResume() {
super.onResume();
Timber.d("retain, onResume");
if(!called) {
new RecordDataFragment.TestTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
called = true;
}
}
}
2019-11-22 12:28:55.503 D/RecordDataFragment: retain, onAttach
2019-11-22 12:32:00.263 D/RecordFragment: retain, onViewStateRestored
2019-11-22 12:32:03.538 D/RecordFragment: retain, onResume
2019-11-22 12:32:03.544 D/RecordDataFragment$TestTask: retain, looping.
2019-11-22 12:32:07.273 D/RecordDataFragment: retain, onDetach
2019-11-22 12:32:07.297 D/RecordDataFragment$TestTask: retain, exit looping.
2019-11-22 12:32:07.403 D/RecordFragment: retain, onDestroy
2019-11-22 12:32:07.566 D/RecordDataFragment: retain, onAttach
2019-11-22 12:32:08.621 D/RecordFragment: retain, onViewStateRestored
2019-11-22 12:32:08.870 D/RecordFragment: retain, onResume
2019-11-22 12:32:09.663 D/RecordDataFragment$TestTask: retain, onPostExecute