質問

I'm facing what I would expect to be a common problem, but I haven't been able to find an existing solution. I want to make sure I'm not reinventing the wheel before I roll my own.

Some time ago, I wrote a Bluetooth serial library in which a worker thread establishes the socket connection and then reads from it, posting callbacks in the UI thread whenever data is received. My rationale is that you typically want to do I/O (especially blocking I/O) outside the UI thread, so why not let the library take care of it? The app just needs to implement the callback interface to handle incoming data. Something like this:

public interface ConnectorListener {
   void onData(BluetoothConnector connector, byte[] data);
}

Now I want to generalize my interfaces to handle other serial byte sources and sinks. So once again, I'm casting around to see if there's an existing interface that I could use...

役に立ちましたか?

解決

The closest thing I've found is AsynchronousByteChannel. With this interface, you initiate a read and get a callback to your CompletionHandler when data arrives. This is slightly different from my original idea of a "live source" that would read constantly, making multiple callbacks.

Anyway, it's moot because AsynchronousByteChannel was added in Java 1.7 and is not available on Android. I might copy it to make standardizing my code easier in the event it does become available.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top