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)

Unreachable code, but reachable with exception

Can't find the Shader/UVs tab

Do items de-spawn in Diablo?

Why does Captain Marvel assume the planet where she lands would recognize her credentials?

PTIJ: How can I halachically kill a vampire?

Who deserves to be first and second author? PhD student who collected data, research associate who wrote the paper or supervisor?

A question on the ultrafilter number

How are such low op-amp input currents possible?

Could you please stop shuffling the deck and play already?

If the Captain's screens are out, does he switch seats with the co-pilot?

Why is this plane circling around the Lucknow airport every day?

Subset counting for even numbers

Am I not good enough for you?

Why does Deadpool say "You're welcome, Canada," after shooting Ryan Reynolds in the end credits?

Making a sword in the stone, in a medieval world without magic

Good allowance savings plan?

Built-In Shelves/Bookcases - IKEA vs Built

How do you like my writing?

Virginia employer terminated employee and wants signing bonus returned

Does splitting a potentially monolithic application into several smaller ones help prevent bugs?

Could a cubesat propel itself to Mars?

My story is written in English, but is set in my home country. What language should I use for the dialogue?

Can someone explain what is being said here in color publishing in the American Mathematical Monthly?

In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?



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
    Mar 7 at 2:30











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

    – vvy
    Mar 7 at 3:08











  • 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
    Mar 7 at 5:28











  • @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
    Mar 7 at 5:30











  • 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
    Mar 7 at 6:42
















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
    Mar 7 at 2:30











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

    – vvy
    Mar 7 at 3:08











  • 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
    Mar 7 at 5:28











  • @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
    Mar 7 at 5:30











  • 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
    Mar 7 at 6:42














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 Mar 6 at 16:25







vvy

















asked Mar 6 at 16:10









vvyvvy

4171930




4171930












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

    – Choim
    Mar 7 at 2:30











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

    – vvy
    Mar 7 at 3:08











  • 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
    Mar 7 at 5:28











  • @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
    Mar 7 at 5:30











  • 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
    Mar 7 at 6:42


















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

    – Choim
    Mar 7 at 2:30











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

    – vvy
    Mar 7 at 3:08











  • 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
    Mar 7 at 5:28











  • @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
    Mar 7 at 5:30











  • 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
    Mar 7 at 6:42

















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

– Choim
Mar 7 at 2:30





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

– Choim
Mar 7 at 2:30













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

– vvy
Mar 7 at 3:08





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

– vvy
Mar 7 at 3:08













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
Mar 7 at 5:28





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
Mar 7 at 5:28













@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
Mar 7 at 5:30





@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
Mar 7 at 5:30













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
Mar 7 at 6:42






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
Mar 7 at 6:42













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 Mar 7 at 6:44









        TommyTommy

        4,0293831




        4,0293831





























            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

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко