Hi all,
I am creating an application that reads from different sensors and display the result on android app. I am using bluetooth communication. I am able to write (Send data) but I am not able read data. This is what I did:
1- I created a bluetoothCommunication class and extended it to Application
2- Call (BluetoothCommunication) getApplication on every activity.
Here is my code for BluetoothCommunication:
My Reading Activity:
I am creating an application that reads from different sensors and display the result on android app. I am using bluetooth communication. I am able to write (Send data) but I am not able read data. This is what I did:
1- I created a bluetoothCommunication class and extended it to Application
2- Call (BluetoothCommunication) getApplication on every activity.
Here is my code for BluetoothCommunication:
Java:
package com.example.ibm.exoskeleton_3;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
/**
* Created by IBM on 07-Apr-15.
*/
public class BluetoothCommunication extends Application
{
Handler h;
int RECIEVE_MESSAGE = 1;
public static final String TAG = "bluetooth3";
public ConnectedThread mConnectedThread;
public BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter;
public BluetoothSocket btSocket = null;
BluetoothDevice mdevice = btAdapter.getRemoteDevice(address);
// SPP UUID service
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
public static String address = "00:06:66:68:30:D6";
@Override
public void onCreate () {
super.onCreate();
try {
btSocket = createBluetoothSocket(mdevice);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
try {
btSocket = mdevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
try {
createBluetoothSocket(mdevice);
} catch (IOException e) {
e.printStackTrace();
}
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
public BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
public void checkBTState() {
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
BluetoothCommunication.this.startActivity(enableBtIntent);
}
}
}
public class ConnectedThread extends Thread {
// public final InputStream mmInStream;
public final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
// mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
/*public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}*/
}
public void errorExit(String title, String message){
Toast.makeText(getApplicationContext(), title + " - " + message, Toast.LENGTH_LONG).show();
}
public BluetoothAdapter getBtAdapter()
{
return btAdapter;
}
public BluetoothSocket getBtSocket ()
{
return btSocket;
}
}
My Reading Activity:
Java:
package com.example.ibm.exoskeleton_3;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.IOException;
import java.io.InputStream;
public class OnYourOwn extends Activity {
EditText thumb, index, middle, ring, pinky;
BluetoothCommunication app;
Handler h;
BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
static int check = 1;
Button homescreen;
public BluetoothAdapter btAdapter = null;
final int RECIEVE_MESSAGE = 1; // Status for Handler
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.try_your_own);
app = (BluetoothCommunication) getApplication();
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
app.checkBTState();
final int RECIEVE_MESSAGE = 1; // Status for Handler
run ();
thumb = (EditText) findViewById(R.id.ThumbText);
index = (EditText) findViewById(R.id.IndexText);
middle = (EditText) findViewById(R.id.MiddleText);
ring = (EditText) findViewById(R.id.RingText);
pinky = (EditText) findViewById(R.id.PinkyText);
homescreen = (Button) findViewById(R.id.HomeScreenButton);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
if (check == 1) {
thumb.setText(sbprint);
check = 2;
}// update thumb
else if (check == 2) {
index.setText(sbprint);
check = 3;
}
else if (check == 3) {
middle.setText(sbprint);
check = 4;
}
else if (check == 4) {
ring.setText(sbprint);
check = 5;
}
else {
pinky.setText(sbprint);
check = 1;
}
}
// Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
}
;
};
homescreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(OnYourOwn.this, MainActivity.class);
OnYourOwn.this.startActivity(intent);
}
});
}
/*public void ConnectedThread2 (BluetoothSocket socket) {
InputStream mmInStream;
InputStream tmpIn = null;
try {
socket.connect();
} catch (IOException e) {
e.printStackTrace();
}
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}*/
public void run() {
InputStream mmInStream;
InputStream tmpIn = null;
try {
app.btSocket.connect();
} catch (IOException e) {
e.printStackTrace();
}
try {
tmpIn = app.btSocket.getInputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
}