Android AsyncTask memory leaks

前端 未结 2 839
失恋的感觉
失恋的感觉 2020-12-11 18:27

I read some questions here, some articles in Internet, but the question about memory leaks in AsyncTask isn\'t clear for me. Please, can you give me an advice?
Let\'s co

相关标签:
2条回答
  • 2020-12-11 18:38
    1. Cancelling is a good way to solve your memory leak. You might want to consider cancelling in onStop though, since you set up a new task in onStart. You might want to combine this with dismissing the progressDialog in onStop, since you're cancelling the task.

    2. If you cancel the task, you will not cause a memory leak. If you don't, you might cause a temporary memory leak. You could for example solve that by constructing the new Java file with a context.getApplicationContext() instead of normal getContext / this (Activity). Then it will not be tied to the activity but to the application (the application survives orientation change). You however won't be able to access the dialog in onPostExecute(). Instead you could use a callback to a listener if you want. Make the activity implement the listener (and detach it onStop). But cancelling is a fine approach as well.

    0 讨论(0)
  • 2020-12-11 18:52

    By the way cancelling an async task doesn't mean that it will immediately be cancelled. I recommend you to switch to Intent Services, Handlers or if possible to RXJava.

    Unlike async tasks where you may need to nest async tasks to execute multiple executions, with RXJava you could chain those executions, apply filters and different transformations and you can run that code on a worker thread.

    0 讨论(0)
提交回复
热议问题