2

I defined a base class extends AsyncTask and have some custom method. I want to create some child classes which extend this, and override some methods. But by this way, its field will leaks the Context object.

abstract class ParentTask(context: Context) : AsyncTask<Void, Int, String>() 
{
    ...
    override fun doInBackground(vararg params: Void): String? {
        ...
    }
    ...
}

Please tell me why and show me how to implement it in Android Kotlin? I'm very appreciated if there's an example about this. p/s : I'm searched for this but can't understand. Why using Singleton, or other design pattern

7
  • As long as context is context.applicationContext you'll leak no activity. Commented Sep 4, 2017 at 4:39
  • Do you mean the context in the constructor? How will this be leaked? Commented Sep 4, 2017 at 5:06
  • @s1m0nw All View field in this class also have this warning. I don't know exactly how it leak. I think it only happen when define Context in an 'object' in Kotlin Commented Sep 4, 2017 at 6:25
  • @EugenPechanec In Android Studio, there's a warning at line : var context: Context Somebody tell that let using internal class. But I have any idea about my case Commented Sep 4, 2017 at 6:27
  • 1
    @s1m0nw1 This field leaks a context object less... A static field will leak contexts. Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a Fragment or Activity, then this reference means that the long-running handler/loader/task will hold a reference to the activity which prevents it from getting garbage collected. Similarly, direct field references to activities and fragments from these longer running instances can cause leaks. ViewModel classes should never point to Views or non-application Contexts. Commented Sep 4, 2017 at 6:31

1 Answer 1

4

You can't avoid this warning this way, but you can handle that your context is application context and it won't leak:

    abstract class ParentTask(context: Context) : AsyncTask<Void, Int, String>() {
        private val context: Context

        init {
            this.context = context.applicationContext
        }

        override fun doInBackground(vararg voids: Void): String? {
            //...
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.