Back to project page SamyGo-Android-Remote.
The source code is released under:
GNU General Public License
If you think the Android project SamyGo-Android-Remote listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package de.quist.samy.remocon; // w w w. ja v a 2 s . c o m import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.InterruptedIOException; import java.io.Reader; import java.util.Arrays; public class RemoteReader { public interface ReplyHandler { void onRegistrationSuccessfull(); void onRegistrationDenied(); void onRegistrationTimeout(); void onUnknownStatus(char[] status); void onClose(IOException e); } private static final char[] REGISTRATION_ALLOWED = new char[] {0x64, 0x00, 0x01, 0x00}; private static final char[] REGISTRATION_DENIED = new char[] {0x64, 0x00, 0x00, 0x00}; private static final char[] REGISTRATION_TIMEOUT = new char[] {0x65, 0x00}; private static final char[] EVERYTHING_IS_FINE = new char[] {0x00, 0x00, 0x00, 0x00}; private InputStream in; private ReplyHandler handler; private Thread worker; private InputStreamReader reader; private boolean active; RemoteReader(InputStream in, ReplyHandler handler) { this.in = in; this.handler = handler; } public synchronized void start() { if (active) return; this.reader = new InputStreamReader(in); active = true; this.worker = new Thread(new Runnable() { public void run() { try { work(); } catch (IOException e) { if (active) { handler.onClose(e); } active = false; } } }); this.worker.start(); } private void work() throws IOException, InterruptedIOException { while (active) { int messageType = reader.read(); String identifier = readText(reader); char[] status = readCharArray(reader); if (Arrays.equals(REGISTRATION_ALLOWED, status)) { handler.onRegistrationSuccessfull(); } else if (Arrays.equals(REGISTRATION_DENIED, status)) { handler.onRegistrationDenied(); } else if (Arrays.equals(REGISTRATION_TIMEOUT, status)) { handler.onRegistrationTimeout(); } else { handler.onUnknownStatus(status); } } } private static String readText(Reader reader) throws IOException { char[] buffer = readCharArray(reader); return new String(buffer); } private static char[] readCharArray(Reader reader) throws IOException { if (reader.markSupported()) reader.mark(1024); int length = reader.read(); int delimiter = reader.read(); if (delimiter != 0) { if (reader.markSupported()) reader.reset(); throw new IOException("Unsupported reply exception"); } char[] buffer = new char[length]; reader.read(buffer); return buffer; } public synchronized void stop() { if (!active) return; this.active = false; if (this.worker != null) { try { in.close(); } catch (IOException e) { } worker.interrupt(); } } }