异步任务和上下文 [英] AsyncTask and Contexts

查看:41
本文介绍了异步任务和上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I'm working out my first multi-threaded application using Android with the AsyncTask class. I'm trying to use it to fire off a Geocoder in a second thread, then update the UI with onPostExecute, but I keep running into an issue with the proper Context.

我在主线程上使用 Contexts 有点犹豫,但我不确定 Context 是什么或如何在后台线程上使用它,而且我还没有找到任何关于它的好例子.有什么帮助吗?这是我正在尝试做的事情的摘录:

I kind of hobbled my way through using Contexts on the main thread, but I'm not exactly sure what the Context is or how to use it on background threads, and I haven't found any good examples on it. Any help? Here is an excerpt of what I'm trying to do:

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);
  }
}

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

It keeps failing at the sixth line there, because of the improper Context.

推荐答案

@Eugene van der Merwe

@Eugene van der Merwe

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

The following piece of code works for me : ) -->

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

Ready4Android

这篇关于异步任务和上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆