gpt4 book ai didi

java - AsyncTask 和上下文

转载 作者:IT老高 更新时间:2023-10-28 21:00:29 26 4
gpt4 key购买 nike

所以我正在使用带有 AsyncTask 类的 Android 开发我的第一个多线程应用程序。我正在尝试使用它在第二个线程中触发地理编码器,然后使用 onPostExecute 更新 UI,但我一直遇到正确上下文的问题。

我在主线程上使用 Contexts 时有点步履蹒跚,但我不确定 Context 是什么或如何在后台线程上使用它,而且我还没有找到任何好的例子。有什么帮助吗?这是我正在尝试做的摘录:

public class GeoCode extends AsyncTask<GeoThread, Void, GeoThread> {
@Override
protected GeoThread doInBackground(GeoThread... i) {
List<Address> addresses = null;
Geocoder geoCode = null;
geoCode = new Geocoder(null); //Expects at minimum Geocoder(Context context);
addresses = geoCode.getFromLocation(GoldenHour.lat, GoldenHour.lng, 1);
}
}

由于上下文不正确,它一直在第六行失败。

最佳答案

@Eugene van der Merwe

以下代码对我有用:) -->

public class ApplicationLauncher extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.applicationlauncher);

LoadApplication loadApplication = new LoadApplication(this);
loadApplication.execute(null);
}

private class LoadApplication extends AsyncTask {

Context context;
ProgressDialog waitSpinner;
ConfigurationContainer configuration = ConfigurationContainer.getInstance();

public LoadApplication(Context context) {
this.context = context;
waitSpinner = new ProgressDialog(this.context);
}

@Override
protected Object doInBackground(Object... args) {
publishProgress(null);
//Parsing some stuff - not relevant
configuration.initialize(context);
return null;
}

@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
// Only purpose of this method is to show our wait spinner, we dont
// (and can't) show detailed progress updates
waitSpinner = ProgressDialog.show(context, "Please Wait ...", "Initializing the application ...", true);
}

@Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
waitSpinner.cancel();
}
}
}

干杯,

Ready4Android

关于java - AsyncTask 和上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1912725/

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