On Wed, Dec 7, 2011 at 6:35 PM, Vincent <[email protected]> wrote: > Thank you. > > I created a global variable int N and a boolean FLAG > > and use a method to initiate > > void function() { > N = 0; > FLAG_COMMAND = true; > mService.write(command((byte) N)); > } > > > > private final Handler mHandler = new Handler() > { > @Override > public void handleMessage(Message msg) { > switch (msg.what) { > case MESSAGE_READ: > byte[]readBuf = (byte[]) msg.obj; > > Packet rPacket = new Packet(readBuf); > > if (FLAG_COMMAND && N <= 10) { > if (rPacket.isValid()) { > doSomething(rPacket); > N++; > } else { > N--; > } > mService.write(command((byte) N)); > } else if (N >= 10) { > FLAG_COMMAND = false; > N = 0; > } > break; > } > } > } > > > Now it works, but the code is dirty and inefficient, I want to know how to > do it in a normal way, but not "Trying to shoehorn the synchronous model > into the asynchronous model".
Uhh, nope, what's dirty and inefficient about it? This is how you write asynchronous code. The hacky way is to spin off a thread that does the processing and wait on a condition variable until that thread changes something, then dispatch a new communication (actually, I don't even think that would work in this case, ..). I can see where you might say the code is "dirty," but I don't know why you would think the code is inefficient. By the way, you define that code function(), but you never *call* it, what's that about? Are you intending that it will just do the init stuff? Anyway, this is how people write asynchronous handlers, so it's supposed to look something like this.. (By the way, the fact that sometimes your package is malformed probably reveals something bad, but I'm not commenting on your protocol, just your implementation...) kris P.s., and those aren't global variables, they're just instance variables, I'm assuming.. -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/android-developers?hl=en

