views:

215

answers:

2

This question is related to an existing question I asked. I though I'll ask a new question instead of replying back to the other question. Cannot "comment" on my previous question because of a word limit.

Marc wrote - I've more than one Handlers in an Activity." Why? If you do not want a complicated handleMessage() method, then use post() (on Handler or View) to break the logic up into individual Runnables. Multiple Handlers makes me nervous. I'm new to Android. Is having multiple handlers in a single activity a bad design ?

I'm new to Android. My question is - is having multiple handlers in a single activity a bad design ?

Here is the sketch of my current implementation.

I've a mapActivity that creates a data thread (a UDP socket that listens for data). My first handler is responsible for sending data from the data thread to the activity.

On the map I've a bunch of "dynamic" markers that are refreshed frequently. Some of these markers are video markers i.e., if the user clicks a video marker, I add a ViewView that extends a android.opengl.GLSurfaceView to my map activity and display video on this new vide. I use my second handler to send information about the marker that the user tapped on ItemizedOverlay onTap(int index) method.

The user can close the video view by tapping on the video view. I use my third handler for this.

I would appreciate if people can tell me what's wrong with this approach and suggest better ways to implement this.

Thanks.

+2  A: 

As I wrote in my previous comment, I would not use multiple Handler objects for that.

With respect to the UDP socket thread, you can either stick with your existing Handler, or use post() on your MapView to post a Runnable to the main application thread, or use runOnUiThread() on your MapActivity.

With respect to your "second handler to send information about the marker that the user tapped on ItemizedOverlay onTap(int index) method", onTap() will be called on the main application thread, and so you do not need to use a Handler. The same is true for your third Handler.

You only use Handlers -- at most -- when you have to communicate from a background thread to the main application thread.

CommonsWare
A: 

I am also facing the same issue with multiple handlers in my application. We were having handlers for various tasks eg. A,B,C...etc. we used somethhing like A_handler,B_handler,C_handler which increased to code complexity and management and then registering and unregistering each one. A generic approach was adopted for putting the handlers in an ArrayList and then registering and unregistering all in one go and also using the index to get the handler to notify the activities. I still think we could have done it better. Any suggestions will be useful

vikrant bains