Skip to content Skip to sidebar Skip to footer

Am I Using This Handler And Executor Correctly (Android)?

I have an Executor that run a while true loop that just pings a server with data. Now I need to updated the UI with this data, so I am using a handler. In my main activity I have:

Solution 1:

Answer to your question will be a bit arbitrary. Since the implementation is just a design choice, there won't be right or wrong but would be good or not so good.

Following are points which I would like to highlight:

  • If you are just concerned networkTask.setHandler(generalHandler); then its fine as long as you are not invoking any network call or heavy processing on Main thread.
  • You also need to ensure that your Runnable is interrupted appropriately in apps onStop() or onDestroy() to avoid potential memory leak.
  • You are continuously trying to ping the server which is not a great idea since it will consume resources and drain battery. You can perform these tasks periodically or use FCM push.
  • For closing the InputStreams or OutputStreams its considered good practice to clean up in finally {..} block which guarantees clean up in case some other Exceptions occurs during execution.

One alternative would be to implement ViewModel and MutableLiveData and perform the operation. This will no bloat your Activity with un-necessary processing.


Post a Comment for "Am I Using This Handler And Executor Correctly (Android)?"