android app implementation: MyActivity.java is the main interface, where mHandler receives messages from the peer Bluetooth, BtClientService.java defines the Bluetooth initialization, connection, read and write functions, May I ask how to implement the function of vibrating to remind if no bluetooth data is received from the peer within 10s?
- Message receiving and processing in the MyActivity.mHandler, but this is not appropriate here, here is the processing of received messages;
- InputStream.available() is processed in BtClientService to determine whether the peer data has been received. But the question here is, how to continuously monitor the data reception of the peer within 10s?
Another one, if the peer data is not received within 10s (in BtClientService.ConnectThread), how to let MyActivity know? handler. sendMessage?
in MyActivity.mHandler:
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
isReceived = !TextUtils.isEmpty(readMessage.trim());
Log.d(TAG, "mHandler - MESSAGE_READ - isReceived = " + isReceived);
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
in BtClientService.ConnectThread
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created ~ " + e.toString());
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
mState = STATE_CONNECTED;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (mState == STATE_CONNECTED) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected ~ " + e.toString());
connectionLost();
break;
}
}
}