简体   繁体   English

android,带有getApplicationContext()的自定义类

[英]android, custom class with getApplicationContext()

Im developing an app that uses a lot of network requests for data retrieval. 我正在开发一个使用大量网络请求进行数据检索的应用程序。 The network request is currently a URLConnection , with HttpsURLConnection . 该网络请求当前是带有HttpsURLConnectionURLConnection

Issue I've got is that i call getApplicationContext() a couple of times. 我遇到的问题是我多次调用getApplicationContext() This has been fine prior when i declare the class inside of the activity class, however i wish to just have the AsyncTask declared in a separate class, to be imported to activity classes where needed. 当我在活动类中声明该类之前,这很好,但是我希望仅在单独的类中声明AsyncTask,以便在需要时将其导入到活动类中。 I'm assuming that i cannot getApplicationContext() from the custom class as it is not extending the activity. 我假设我不能从自定义类获取getApplicationContext() ,因为它没有扩展活动。 How would i resolve this? 我该如何解决? Can i pass the context as a parameter when i instantiate it? 实例化时可以传递上下文作为参数吗?


would something like this work: 会像这样的工作:

 Context contxt = getApplicationContext(); CustomClass custmClass = new CustomClass(); ArrayList<Object> parameters = new ArrayList<Object>(); parameters.add(contxt); ... custmClass.execute(parameters); 

Where CustomClass extends AsyncTask<ArrayList<Object>, Void, Boolean> ? CustomClass extends AsyncTask<ArrayList<Object>, Void, Boolean>在哪里CustomClass extends AsyncTask<ArrayList<Object>, Void, Boolean>

As told in the other answers, you should pass the context as a parameter to your AsyncTask. 如其他答案所述,您应该将上下文作为参数传递给AsyncTask。 Still, you can got lots of problems doing this, if you close your activity for example while the AsyncTask is executing and using this reference this will cause an exception. 但是,这样做仍然会遇到很多问题,例如,如果在执行AsyncTask时关闭活动,并使用此引用,则会导致异常。

To prevent this, avoid having a strong reference to your activity as mentioned in the other posts and use weak references. 为避免这种情况,请避免像其他帖子中所提到的那样强烈引用您的活动,并使用弱引用。 Make sure you always check if the return value of your weak reference is null. 确保始终检查弱引用的返回值是否为空。

Example : 范例:

import com.example.MyActivity;

public class MyTask {

    private final WeakReference<MyActivity> myActivity;

    public MyTask(MyActivity myActivity) {
        this.myActivity = new WeakReference<MyActivity>(myActivity);
    }

    private AsyncTask<String, Integer, Integer> createAsyncTask() {
        return new AsyncTask<String, Integer, Integer>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // prepare execution
            }

            @Override
            protected Integer doInBackground(String... params) {
                // code
                return 0;
            }

            @Override
            protected void onPostExecute(Integer result) {
                if (myActivity.get() != null && !myActivity.get().isFinishing()) {
                    // do something
                }
            }
        };
    }

}

in one of your activities (the main activity is better) declare this 在您的一项活动(主要活动更好)中声明

public static Context context;

in your oncreate add this 在您的oncreate中添加此

 context=getApplicationContext();

and in other classes just use 在其他类别中只需使用

MainActivity.context

this works for me 这对我有用

Can i pass the context as a parameter when i instantiate it? 实例化时可以传递上下文作为参数吗?

Yes. 是。 You can pass current Context as parameter to your custom class. 您可以将当前Context作为参数传递给自定义类。

1st Way: 第一种方式:

Create single Argument Constructor in your Custom Classs 在自定义类中创建单个参数构造函数

Context myCon;

public myClass(Context mCon){
 this.myCon=mCon;
}

And you can access in your Activity like 您可以像这样访问您的Activity

myClass mc=new myClass(Activity.this);

2nd Way: 第二种方式:

By passing to Custom class method directly 通过直接传递给Custom类方法

public void getCount(Context mCon){
 //Directly used mCon here
}

Current Solution: 当前解决方案:

Context contxt = getApplicationContext();
CustomClass custmClass = new CustomClass(contxt);
ArrayList<Object> parameters = new ArrayList<Object>();
parameters.add(contxt);
...
custmClass.execute(parameters);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM