gpt4 book ai didi

android - AsyncTask 的 onPostExecute() 中的上下文是什么?

转载 作者:行者123 更新时间:2023-11-29 00:39:06 25 4
gpt4 key购买 nike

我在 Activities 中确实使用了很多 AsyncTasks 作为私有(private)内部类。从一开始就让我困惑的一件事是我在 onPostExecute() 中获得了什么上下文?

如果您查看下面显示的精简示例,您可以在 onPostExecute() 中使用 getString()。该调用使用什么上下文? Activity 可能在 doInBackground 期间发生了变化(例如 OrientationChange),因此它不可能是那个上下文。

目前我正在修补 Activity 上下文 (task.context = this) 并使用该特定上下文 (context.getString())。

我的问题:在不使用周围 Activity 的上下文的情况下,在内部类 AsyncTask 的 onPostExecute() 中使用 getString() 是否省事?

非常感谢。

public class MyActivity extends Activity {

/* package */ MyActivity context;

private class MyAsyncTask extends AsyncTask<Void, Void, Void> {

public MyAsyncTask(final MyActivity context) {
super();

this.context = context;
}

@Override
protected Cursor doInBackground(/* ... */) {
// ...
}

@Override
protected void onPostExecute(/* ... */) {
if (context != null) {
// Currently I do use that
String s = context.getString(R.string.mytext);
context.task = null;
}

// Would this be save?
String s2 = getString(R.string.mytext);
}

@Override
protected void onPreExecute (/* ... */) {
// ...
}
}

/* package */ MyAsyncTask task;

@Override
public void onCreate(final Bundle bundle) {
// ...

Bundle bundleExtras = getIntent().getExtras();
if (bundleExtras != null) {
task = (MyAsyncTask) getLastNonConfigurationInstance();
if (task != null) {
task.context = this;
// ...
} else {
task = new MyAsyncTask(this);
task.execute();
}
}
}

@Override
public Object onRetainNonConfigurationInstance() {
if (task != null) {
// ...
task.context = null;
}

return task;
}
}

最佳答案

Is it save to use getString() within onPostExecute() of an Inner Class AsyncTask without using the context of the surrounding Activity?

不,这不安全。作为该 Activity 中的内部类,您的 MyAsyncTask 类在创建时将引用 MyActivity。因此,如果 MyActivity 由于任何原因(如轮换)被终止,在 onPostExecute 回调中,您将以 MyAsyncTask 持有对的引用而告终杀死的 MyActivity 实例。

使用对 Activity 的引用更安全,因为您将该引用更新为始终指向 MyActivity 的有效实例。也许您还想直接在 onRetainNonConfigurationInstance 中使用 null 使 Activity 无效,以确保您不会触摸它(如果 MyAsyncTask 到达 onPostExecute 直到你再次设置 MyActivity)直到你有一个有效的引用。

关于android - AsyncTask 的 onPostExecute() 中的上下文是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10650366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com