나는 블루투스를 통해 PC와 통신하는 Android 앱을 작성 중이다. 정상적인 작동 중에는 전화기에서 PC로 짧은 8 바이트 패킷의 빠른 연속을 일반적으로 100Hz 이상으로 보냅니다.표준 Java에서 Android Message Handler 패턴을 구현하는 방법은 무엇입니까?
각 장치에서 쓰기 및 읽기를 실행하는 별도의 스레드가 실행 중입니다. 코드는 다음과 같습니다.
/**
* The Class ProcessConnectionThread.
*/
public class ConnectedThread extends Thread {
/** The m connection. */
private StreamConnection mmConnection;
InputStream mmInputStream;
OutputStream mmOutputStream;
private boolean mmCanceled = false;
/**
* Instantiates a new process connection thread.
*
* @param connection
* the connection
*/
public ConnectedThread(StreamConnection connection) {
mmConnection = connection;
// prepare to receive data
try {
mmInputStream = mmConnection.openInputStream();
mmOutputStream = mmConnection.openOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
byte[] buffer;
int bytes;
// Keep listening to the InputStream while connected
while (!mmCanceled) {
try {
buffer = ByteBufferFactory.getBuffer();
// Read from the InputStream
bytes = mmInputStream.read(buffer);
if(bytes > 0)
onBTMessageRead(buffer, bytes);
else
ByteBufferFactory.releaseBuffer(buffer);
} catch (IOException e) {
MyLog.log("Connection Terminated");
connectionLost();//Restarts service
break;
}
}
if(!mmCanceled){
onBTError(ERRORCODE_CONNECTION_LOST);
}
}
/**
* Write to the connected OutStream.
*
* @param buffer
* The bytes to write
* @param length
* the length
*/
public void write(byte[] buffer, int length) {
try {
mmOutputStream.write(buffer, 0, length);
// Share the sent message back to the UI Activity
onBTMessageWritten(buffer, length);
} catch (IOException e) {
MyLog.log("Exception during write:");
e.printStackTrace();
}
}
/**
* Cancel.
*/
public void cancel() {
try {
mmCanceled = true;
mmInputStream.close();
mmConnection.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Android 측 코드는 거의 동일하며 스트림 연결 대신 BluetoothSocket을 사용합니다.
큰 차이는 onBTMessageRead(buffer, bytes);
안드로이드 기능에 있습니다
protected void onBTMessageRead(byte[] buffer, int length) {
if (mHandler != null) {
mHandler.obtainMessage(BluetoothService.MESSAGE_READ, length, -1,
buffer).sendToTarget();
}
}
PC 서버 기능 :
protected void onBTMessageRead(byte[] message, int length) {
if (mEventListener != null) {
mEventListener.onBTMessageRead(message, length);
}
// Release the buffer
ByteBufferFactory.releaseBuffer(message);
}
안드로이드는 메시지가 될 수있는 핸들러 - 루퍼/메시지 패턴을 제공합니다 스레드를 통해 전송됩니다. 이렇게하면 읽기가 가능한 빨리 수행되고 메시지 처리가 다른 스레드에 대기합니다. My ByteBufferFactory는 스레드간에 리소스가 올바르게 공유되도록합니다.
현재 PC 쪽에서 구현 된 이벤트 리스너 패턴 만 있습니다.하지만 PC 쪽에서도 유사한 메시지 전달 패턴이 필요합니다. 현재 이벤트 리스너는 ConnectedThread를 방해하여 주요 통신 지연을 일으 킵니다.
Java의 한 스레드에서 메시지를 보내고 다른 스레드에서 FIFO 순서로 비동기 적으로 처리하는 방법이 있습니까?
나는 이것을하려고 생각했지만, 최후의 수단 이죠. 나는 하나의 표준 자바 접근 방식을 사용하는 것을 선호한다. – CodeFusionMobile
나도 알아, 그 이상적인 솔루션은 ... 난 그냥 봤는데이 발견 : http://code.google.com/p/simple-mq/ 어쩌면 그것은 당신에게 조금 도움이 –
작동하도록했습니다. 많은 기능이 안드로이드 플랫폼에 직접 묶여서 제거되어야하기 때문에 박탈 된 버전을 구현했습니다. – CodeFusionMobile