How to get past the memory leak warning (creating a sigleton class that extends the AsyncTask)2019 Community Moderator ElectionUsing UDP to update a list of objects to be renderedHow to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?No UDP broadcast packets after sleep mode on android (not in sleep mode)AsyncTask memory leakAndroid: how to send UDP packet using thread or asynctaskAsyncTask *occasionally* getting stuck with connection timeout/error problems, potential memory leak or Android Studio bug?Warning: This AsyncTask class should be static or leaks might occurCreate class extend AsyncTask without leaking context object in Android KotlinUsing AsyncTask to send a single UDP packetApp crash when use mobie data (3g/4g)

What is the orbit and expected lifetime of Crew Dragon trunk?

Professor forcing me to attend a conference, I can't afford even with 50% funding

A running toilet that stops itself

Rationale to prefer local variables over instance variables?

What is 'Log Memory' in Query Store 2017

Does the US political system, in principle, allow for a no-party system?

What is better: yes / no radio, or simple checkbox?

Where is the License file location for Identity Server in Sitecore 9.1?

Will the concrete slab in a partially heated shed conduct a lot of heat to the unconditioned area?

Why restrict private health insurance?

What is the purpose of a disclaimer like "this is not legal advice"?

Create chunks from an array

The (Easy) Road to Code

How does a sound wave propagate?

If nine coins are tossed, what is the probability that the number of heads is even?

Is this Paypal Github SDK reference really a dangerous site?

Ultrafilters as a double dual

Can Witch Sight see through Mirror Image?

Paper published similar to PhD thesis

Limpar string com Regex

How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?

After Brexit, will the EU recognize British passports that are valid for more than ten years?

Too soon for a plot twist?

Should I file my taxes? No income, unemployed, but paid 2k in student loan interest



How to get past the memory leak warning (creating a sigleton class that extends the AsyncTask)



2019 Community Moderator ElectionUsing UDP to update a list of objects to be renderedHow to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?No UDP broadcast packets after sleep mode on android (not in sleep mode)AsyncTask memory leakAndroid: how to send UDP packet using thread or asynctaskAsyncTask *occasionally* getting stuck with connection timeout/error problems, potential memory leak or Android Studio bug?Warning: This AsyncTask class should be static or leaks might occurCreate class extend AsyncTask without leaking context object in Android KotlinUsing AsyncTask to send a single UDP packetApp crash when use mobie data (3g/4g)










0















I have created a UDP communication application and it is working very well (so far). To receive UDP packets I am using an AsyncTask extension class.



For the sake of clarity (and brevity) I have divided the code into separate kotlin files.



MainActivity.kt handles the UI stuff like button press and creating objects
LongTask.kt defines a LongTask class that extends the AsyncTask (UDP receiver code)



I create a instance of LongTask on a button press event using the following



task = object : LongTask("$idx")
override fun onProgressUpdate(vararg values: String?)
super.onProgressUpdate(*values)
Log.d(TAG, "On UI thread")



task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "")


However, the above lines of code are highlighted in yellow and keep warning of a possible memory leak.



How to write a leak proof code to get past this warning?










share|improve this question
























  • do you need to access activity's variables from LongTask?

    – Choim
    2 days ago











  • @Choim I need to get received UDP data from the AsyncTask regularly and use it for some processing.

    – vvy
    2 days ago











  • your task is anonymous class. So, it has reference to outer class(MainActivity). Therefore, if LongTask is not released, MainActivity would be leaked. Ignore warning with making sure you have to release task or Make LongTask be static class.

    – Choim
    yesterday











  • @Choim I want to make LongTask static and I looked into few answers over web but couldn't follow. Can you add that as an answer?

    – vvy
    yesterday











  • You might want to try doing this as a bound service instead that runs on it's own thread. Your activity can bind to this service, and unbind to it when it's done allowing you a chance to clean up properly. See developer.android.com/guide/components/bound-services

    – Eugene
    yesterday
















0















I have created a UDP communication application and it is working very well (so far). To receive UDP packets I am using an AsyncTask extension class.



For the sake of clarity (and brevity) I have divided the code into separate kotlin files.



MainActivity.kt handles the UI stuff like button press and creating objects
LongTask.kt defines a LongTask class that extends the AsyncTask (UDP receiver code)



I create a instance of LongTask on a button press event using the following



task = object : LongTask("$idx")
override fun onProgressUpdate(vararg values: String?)
super.onProgressUpdate(*values)
Log.d(TAG, "On UI thread")



task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "")


However, the above lines of code are highlighted in yellow and keep warning of a possible memory leak.



How to write a leak proof code to get past this warning?










share|improve this question
























  • do you need to access activity's variables from LongTask?

    – Choim
    2 days ago











  • @Choim I need to get received UDP data from the AsyncTask regularly and use it for some processing.

    – vvy
    2 days ago











  • your task is anonymous class. So, it has reference to outer class(MainActivity). Therefore, if LongTask is not released, MainActivity would be leaked. Ignore warning with making sure you have to release task or Make LongTask be static class.

    – Choim
    yesterday











  • @Choim I want to make LongTask static and I looked into few answers over web but couldn't follow. Can you add that as an answer?

    – vvy
    yesterday











  • You might want to try doing this as a bound service instead that runs on it's own thread. Your activity can bind to this service, and unbind to it when it's done allowing you a chance to clean up properly. See developer.android.com/guide/components/bound-services

    – Eugene
    yesterday














0












0








0








I have created a UDP communication application and it is working very well (so far). To receive UDP packets I am using an AsyncTask extension class.



For the sake of clarity (and brevity) I have divided the code into separate kotlin files.



MainActivity.kt handles the UI stuff like button press and creating objects
LongTask.kt defines a LongTask class that extends the AsyncTask (UDP receiver code)



I create a instance of LongTask on a button press event using the following



task = object : LongTask("$idx")
override fun onProgressUpdate(vararg values: String?)
super.onProgressUpdate(*values)
Log.d(TAG, "On UI thread")



task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "")


However, the above lines of code are highlighted in yellow and keep warning of a possible memory leak.



How to write a leak proof code to get past this warning?










share|improve this question
















I have created a UDP communication application and it is working very well (so far). To receive UDP packets I am using an AsyncTask extension class.



For the sake of clarity (and brevity) I have divided the code into separate kotlin files.



MainActivity.kt handles the UI stuff like button press and creating objects
LongTask.kt defines a LongTask class that extends the AsyncTask (UDP receiver code)



I create a instance of LongTask on a button press event using the following



task = object : LongTask("$idx")
override fun onProgressUpdate(vararg values: String?)
super.onProgressUpdate(*values)
Log.d(TAG, "On UI thread")



task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "")


However, the above lines of code are highlighted in yellow and keep warning of a possible memory leak.



How to write a leak proof code to get past this warning?







android kotlin android-asynctask






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago







vvy

















asked 2 days ago









vvyvvy

4151929




4151929












  • do you need to access activity's variables from LongTask?

    – Choim
    2 days ago











  • @Choim I need to get received UDP data from the AsyncTask regularly and use it for some processing.

    – vvy
    2 days ago











  • your task is anonymous class. So, it has reference to outer class(MainActivity). Therefore, if LongTask is not released, MainActivity would be leaked. Ignore warning with making sure you have to release task or Make LongTask be static class.

    – Choim
    yesterday











  • @Choim I want to make LongTask static and I looked into few answers over web but couldn't follow. Can you add that as an answer?

    – vvy
    yesterday











  • You might want to try doing this as a bound service instead that runs on it's own thread. Your activity can bind to this service, and unbind to it when it's done allowing you a chance to clean up properly. See developer.android.com/guide/components/bound-services

    – Eugene
    yesterday


















  • do you need to access activity's variables from LongTask?

    – Choim
    2 days ago











  • @Choim I need to get received UDP data from the AsyncTask regularly and use it for some processing.

    – vvy
    2 days ago











  • your task is anonymous class. So, it has reference to outer class(MainActivity). Therefore, if LongTask is not released, MainActivity would be leaked. Ignore warning with making sure you have to release task or Make LongTask be static class.

    – Choim
    yesterday











  • @Choim I want to make LongTask static and I looked into few answers over web but couldn't follow. Can you add that as an answer?

    – vvy
    yesterday











  • You might want to try doing this as a bound service instead that runs on it's own thread. Your activity can bind to this service, and unbind to it when it's done allowing you a chance to clean up properly. See developer.android.com/guide/components/bound-services

    – Eugene
    yesterday

















do you need to access activity's variables from LongTask?

– Choim
2 days ago





do you need to access activity's variables from LongTask?

– Choim
2 days ago













@Choim I need to get received UDP data from the AsyncTask regularly and use it for some processing.

– vvy
2 days ago





@Choim I need to get received UDP data from the AsyncTask regularly and use it for some processing.

– vvy
2 days ago













your task is anonymous class. So, it has reference to outer class(MainActivity). Therefore, if LongTask is not released, MainActivity would be leaked. Ignore warning with making sure you have to release task or Make LongTask be static class.

– Choim
yesterday





your task is anonymous class. So, it has reference to outer class(MainActivity). Therefore, if LongTask is not released, MainActivity would be leaked. Ignore warning with making sure you have to release task or Make LongTask be static class.

– Choim
yesterday













@Choim I want to make LongTask static and I looked into few answers over web but couldn't follow. Can you add that as an answer?

– vvy
yesterday





@Choim I want to make LongTask static and I looked into few answers over web but couldn't follow. Can you add that as an answer?

– vvy
yesterday













You might want to try doing this as a bound service instead that runs on it's own thread. Your activity can bind to this service, and unbind to it when it's done allowing you a chance to clean up properly. See developer.android.com/guide/components/bound-services

– Eugene
yesterday






You might want to try doing this as a bound service instead that runs on it's own thread. Your activity can bind to this service, and unbind to it when it's done allowing you a chance to clean up properly. See developer.android.com/guide/components/bound-services

– Eugene
yesterday













1 Answer
1






active

oldest

votes


















0














task = object : LongTask("$idx")
override fun onProgressUpdate(vararg values: String?)
super.onProgressUpdate(*values)
Log.d(TAG, "On UI thread")




This line will create an anonymous inner class which extends from LongTask class. An inner class have an implicit reference to their outer class, in this case MainActivity class.



If the activity is finished before the asynctask completed, then the activity will be leaked or not collected by GC because it's still referred by the asynctask.



Solution: To avoid that we should use WeakReference API. In addition, LongTask is a separate class so we need to define an interface to pass data back to the activity.



First, declare an interface



OnProgressUpdateListener.kt



interface OnProgressUpdateListener 
fun onProgressUpdate(vararg values: String?)



Second, modify the asynctask class. Just focus on OnProgressUpdateListener part because I don't know what exactly your class look like.



LongTask.kt



class LongTask(val idx: String, listener: OnProgressUpdateListener) : AsyncTask<String, String, Unit>() 

private val mListener: WeakReference<OnProgressUpdateListener>? = WeakReference(listener)

override fun doInBackground(vararg params: String?)



override fun onProgressUpdate(vararg values: String?)
mListener?.get()?.onProgressUpdate(*values)




Finally, let the activity implements OnProgressUpdateListener.



MainActivity.kt



class MainActivity : AppCompatActivity(), OnProgressUpdateListener 

override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

task = LongTask("$idx", this)
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "")


override fun onProgressUpdate(vararg values: String?)
// Update your progress on UI thread here
Log.d(TAG, "On UI thread")







share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55027516%2fhow-to-get-past-the-memory-leak-warning-creating-a-sigleton-class-that-extends%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    task = object : LongTask("$idx")
    override fun onProgressUpdate(vararg values: String?)
    super.onProgressUpdate(*values)
    Log.d(TAG, "On UI thread")




    This line will create an anonymous inner class which extends from LongTask class. An inner class have an implicit reference to their outer class, in this case MainActivity class.



    If the activity is finished before the asynctask completed, then the activity will be leaked or not collected by GC because it's still referred by the asynctask.



    Solution: To avoid that we should use WeakReference API. In addition, LongTask is a separate class so we need to define an interface to pass data back to the activity.



    First, declare an interface



    OnProgressUpdateListener.kt



    interface OnProgressUpdateListener 
    fun onProgressUpdate(vararg values: String?)



    Second, modify the asynctask class. Just focus on OnProgressUpdateListener part because I don't know what exactly your class look like.



    LongTask.kt



    class LongTask(val idx: String, listener: OnProgressUpdateListener) : AsyncTask<String, String, Unit>() 

    private val mListener: WeakReference<OnProgressUpdateListener>? = WeakReference(listener)

    override fun doInBackground(vararg params: String?)



    override fun onProgressUpdate(vararg values: String?)
    mListener?.get()?.onProgressUpdate(*values)




    Finally, let the activity implements OnProgressUpdateListener.



    MainActivity.kt



    class MainActivity : AppCompatActivity(), OnProgressUpdateListener 

    override fun onCreate(savedInstanceState: Bundle?)
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    task = LongTask("$idx", this)
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "")


    override fun onProgressUpdate(vararg values: String?)
    // Update your progress on UI thread here
    Log.d(TAG, "On UI thread")







    share|improve this answer



























      0














      task = object : LongTask("$idx")
      override fun onProgressUpdate(vararg values: String?)
      super.onProgressUpdate(*values)
      Log.d(TAG, "On UI thread")




      This line will create an anonymous inner class which extends from LongTask class. An inner class have an implicit reference to their outer class, in this case MainActivity class.



      If the activity is finished before the asynctask completed, then the activity will be leaked or not collected by GC because it's still referred by the asynctask.



      Solution: To avoid that we should use WeakReference API. In addition, LongTask is a separate class so we need to define an interface to pass data back to the activity.



      First, declare an interface



      OnProgressUpdateListener.kt



      interface OnProgressUpdateListener 
      fun onProgressUpdate(vararg values: String?)



      Second, modify the asynctask class. Just focus on OnProgressUpdateListener part because I don't know what exactly your class look like.



      LongTask.kt



      class LongTask(val idx: String, listener: OnProgressUpdateListener) : AsyncTask<String, String, Unit>() 

      private val mListener: WeakReference<OnProgressUpdateListener>? = WeakReference(listener)

      override fun doInBackground(vararg params: String?)



      override fun onProgressUpdate(vararg values: String?)
      mListener?.get()?.onProgressUpdate(*values)




      Finally, let the activity implements OnProgressUpdateListener.



      MainActivity.kt



      class MainActivity : AppCompatActivity(), OnProgressUpdateListener 

      override fun onCreate(savedInstanceState: Bundle?)
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)

      task = LongTask("$idx", this)
      task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "")


      override fun onProgressUpdate(vararg values: String?)
      // Update your progress on UI thread here
      Log.d(TAG, "On UI thread")







      share|improve this answer

























        0












        0








        0







        task = object : LongTask("$idx")
        override fun onProgressUpdate(vararg values: String?)
        super.onProgressUpdate(*values)
        Log.d(TAG, "On UI thread")




        This line will create an anonymous inner class which extends from LongTask class. An inner class have an implicit reference to their outer class, in this case MainActivity class.



        If the activity is finished before the asynctask completed, then the activity will be leaked or not collected by GC because it's still referred by the asynctask.



        Solution: To avoid that we should use WeakReference API. In addition, LongTask is a separate class so we need to define an interface to pass data back to the activity.



        First, declare an interface



        OnProgressUpdateListener.kt



        interface OnProgressUpdateListener 
        fun onProgressUpdate(vararg values: String?)



        Second, modify the asynctask class. Just focus on OnProgressUpdateListener part because I don't know what exactly your class look like.



        LongTask.kt



        class LongTask(val idx: String, listener: OnProgressUpdateListener) : AsyncTask<String, String, Unit>() 

        private val mListener: WeakReference<OnProgressUpdateListener>? = WeakReference(listener)

        override fun doInBackground(vararg params: String?)



        override fun onProgressUpdate(vararg values: String?)
        mListener?.get()?.onProgressUpdate(*values)




        Finally, let the activity implements OnProgressUpdateListener.



        MainActivity.kt



        class MainActivity : AppCompatActivity(), OnProgressUpdateListener 

        override fun onCreate(savedInstanceState: Bundle?)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        task = LongTask("$idx", this)
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "")


        override fun onProgressUpdate(vararg values: String?)
        // Update your progress on UI thread here
        Log.d(TAG, "On UI thread")







        share|improve this answer













        task = object : LongTask("$idx")
        override fun onProgressUpdate(vararg values: String?)
        super.onProgressUpdate(*values)
        Log.d(TAG, "On UI thread")




        This line will create an anonymous inner class which extends from LongTask class. An inner class have an implicit reference to their outer class, in this case MainActivity class.



        If the activity is finished before the asynctask completed, then the activity will be leaked or not collected by GC because it's still referred by the asynctask.



        Solution: To avoid that we should use WeakReference API. In addition, LongTask is a separate class so we need to define an interface to pass data back to the activity.



        First, declare an interface



        OnProgressUpdateListener.kt



        interface OnProgressUpdateListener 
        fun onProgressUpdate(vararg values: String?)



        Second, modify the asynctask class. Just focus on OnProgressUpdateListener part because I don't know what exactly your class look like.



        LongTask.kt



        class LongTask(val idx: String, listener: OnProgressUpdateListener) : AsyncTask<String, String, Unit>() 

        private val mListener: WeakReference<OnProgressUpdateListener>? = WeakReference(listener)

        override fun doInBackground(vararg params: String?)



        override fun onProgressUpdate(vararg values: String?)
        mListener?.get()?.onProgressUpdate(*values)




        Finally, let the activity implements OnProgressUpdateListener.



        MainActivity.kt



        class MainActivity : AppCompatActivity(), OnProgressUpdateListener 

        override fun onCreate(savedInstanceState: Bundle?)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        task = LongTask("$idx", this)
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "")


        override fun onProgressUpdate(vararg values: String?)
        // Update your progress on UI thread here
        Log.d(TAG, "On UI thread")








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        TommyTommy

        3,8043831




        3,8043831





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55027516%2fhow-to-get-past-the-memory-leak-warning-creating-a-sigleton-class-that-extends%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme