当屏幕旋转时,有一些代码应该将旧的 AsyncTask 绑定到新的活动:
public class MainActivity extends AppCompatActivity {
MyTask mt;
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("qwe", "create MainActivity: " + this.hashCode());
tv = (TextView) findViewById(R.id.tv);
mt = (MyTask) getLastNonConfigurationInstance();
if (mt == null) {
mt = new MyTask();
mt.execute();
}
// передаем в MyTask ссылку на текущее MainActivity
mt.link(this);
Log.d("qwe", "create MyTask: " + mt.hashCode());
}
public Object onRetainNonConfigurationInstance() {
// удаляем из MyTask ссылку на старое MainActivity
mt.unLink();
return mt;
}
static class MyTask extends AsyncTask<String, Integer, Void> {
MainActivity activity;
// получаем ссылку на MainActivity
void link(MainActivity act) {
activity = act;
}
// обнуляем ссылку
void unLink() {
activity = null;
}
@Override
protected Void doInBackground(String... params) {
try {
for (int i = 1; i <= 10; i++) {
TimeUnit.SECONDS.sleep(1);
publishProgress(i);
Log.d("qwe", "i = " + i + ", MyTask: " + this.hashCode()
+ ", MainActivity: " + activity.hashCode());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
activity.tv.setText("i = " + values[0]);
}
}
}
问题是它public Object onRetainNonConfigurationInstance()
带有红色下划线
启动时出现错误:
D:\User\GitHub\AsyncTaskLesson_6\app\src\main\java\com\semenov\asynctasklesson_6\MainActivity.java:35: error: onRetainNonConfigurationInstance() in MainActivity cannot override onRetainNonConfigurationInstance() in ComponentActivity
public Object onRetainNonConfigurationInstance() {
^
overridden method is final
请告诉我该怎么做
相反
onRetainNonConfigurationInstance()
,使用onRetainCustomNonConfigurationInstance()
a 来获取对象getLastCustomNonConfigurationInstance()
。虽然这些方法已经过时了。最好的选择是使用 Viewmodel。