public class MainActivity extends BaseActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.go)
public void btnClick() {
startActivity(new Intent(this, SecondActivity.class));
}
}
-
public class SecondActivity extends BaseActivity implements TestAsyncTask.Callbacks{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ButterKnife.bind(this);
}
@OnClick(R.id.btn)
public void onClick() {
new TestAsyncTask(this).execute();
}
@Override
public void onResult(String result) {
finish();
}
}
-
public class TestAsyncTask extends AsyncTask<Void, Void, String> {
private WeakReference<Callbacks> mCallbacks;
public TestAsyncTask(Callbacks callbacks) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
public interface Callbacks {
void onResult(String result);
}
@Override
protected String doInBackground(Void... params) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "WOW";
}
@Override
protected void onPostExecute(String result) {
Callbacks callbacks = mCallbacks.get();
if(callbacks != null) {
callbacks.onResult(result);
}
}
}
MainActivity启动SecondActivity。 SecondActivity启动一个AsyncTask,它在十秒后回调onResult。如果我在回调和启动asynctask之间旋转屏幕,则会创建一个新的SecondActivity。因此onResult将被称为旧的SecondActivity。但是为什么finish()完成新的?
我知道编写这样的代码很糟糕。应该取消asynctask或其他东西。但有趣的是为什么会发生这种情况。这是一种未定义的行为吗?
如果您想重现,请考虑克隆https://github.com/guliash/AndroidExplorer/tree/test