在 AsyncTask 类中获取应用程序上下文? [英] getApplicationContext in AsyncTask class?

查看:24
本文介绍了在 AsyncTask 类中获取应用程序上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个私有的 AsyncTask 方法,我想将它们分解为公共外部类.在我的应用程序中,我有一个扩展 Application 的公共类,它包含一些我想从应用程序的不同部分访问的共享例程.然而,当我打破 AsyncTask 类时,我不再能够调用 getApplicationContext() 来获取对我的应用程序库的引用(该类现在没有从 Activity 继承任何内容).getBaseContext() 也会有问题.当 AsyncTask 被实例化并从那里构建时,我应该将它传递给 AsyncTask 吗?不确定那是否安全.

I have a couple private AsyncTask methods that I'd like to break out into public external classes. In my application, I have a public class extending Application which holds some shared routines I want to access from different parts of my application. When I break out the AsyncTask class however, I'm no longer able to call getApplicationContext() to get a reference to my application library (the class does not inherit anything from Activity now). getBaseContext() will have problems as well. Should I be passing a context into the AsyncTask when it gets instantiated and build from there? Not sure if that was safe or not.

import java.util.ArrayList;
import android.os.AsyncTask;

public class DlTask extends AsyncTask
{
    long totalbytes = 0;
    long totalread = 0;
    ArrayList <String> data;

    @Override
    protected void onPreExecute ()
    {   
        AppLib lib = (AppLib) getApplicationContext();

        lib.saveStatusText ("Contacting " + lib.getServerAddress () + ":" + lib.getServerPort () + "...");
       super.onPreExecute ();
    }

      @Override
      protected Object doInBackground (Object... params)
      {
        data = lib.sendCommand (CMD_LIST);
         return true;
      }

      @Override
      protected void onPostExecute (Object result)
      {

         if (data != null)
         {
                    lib.saveStatusText (data.size () + " files found");
         }
         else
         {
            Log.d (TAG, "data is null");
            Toast.makeText (getBaseContext(), msg, Toast.LENGTH_SHORT).show ();                     
         }

         super.onPostExecute(result);
      }

}

推荐答案

当 AsyncTask 被实例化并从那里构建时,我应该将它传递给上下文吗?

Should I be passing a context into the AsyncTask when it gets instantiated and build from there?

您别无选择,因为您将无法通过任何其他方式获得 Context.

You do not have a choice, as you will be unable to get a Context by any other means.

这篇关于在 AsyncTask 类中获取应用程序上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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