How to read out de incoming values send with Bluetooth? - java

I want to use data sent from my Arduino to my android. I'm able to connect both together and display the incoming data on my screen. However, when I want to use the incoming data to set comments this doesn't seem to be working. So how can I get the values out of the incoming data?
String address1 = ("98:D3:81:FD:4B:87");
String name1 = ("Sensor_Shoe");
#SuppressLint("HandlerLeak")
protected void bluetoothconnect() {
btEnablingIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
requestCodeForEnable=1;
if (myBluetoothAdapter==null){
Toast.makeText(getApplicationContext(),"Bluetooth not supported", Toast.LENGTH_LONG).show();
} else {
if (!myBluetoothAdapter.isEnabled()) {
startActivityForResult(btEnablingIntent, requestCodeForEnable);
}
if (myBluetoothAdapter.isEnabled()) {
myBluetoothAdapter.disable();
Toast.makeText(getApplicationContext(),"Bluetooth disabled",Toast.LENGTH_SHORT).show();
TextView input1 = findViewById(R.id.input1); input1.setVisibility(View.INVISIBLE);
ImageButton btn_bluetooth = findViewById(R.id.btn_bluetooth); btn_bluetooth.setBackgroundColor(getResources().getColor(R.color.transparent));
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==requestCodeForEnable){
ImageButton btn_bluetooth = findViewById(R.id.btn_bluetooth);
if(resultCode==RESULT_OK){
Toast.makeText(getApplicationContext(),"Bluetooth enabled",Toast.LENGTH_SHORT).show();
TextView input1 = findViewById(R.id.input1); input1.setVisibility(View.VISIBLE);
btn_bluetooth.setBackgroundColor(getResources().getColor(R.color.colorAccent));
createsocket();
}
else if(resultCode==RESULT_CANCELED){
Toast.makeText(getApplicationContext(),"Bluetooth enabling cancelled",Toast.LENGTH_SHORT).show();
TextView input1 = findViewById(R.id.input1); input1.setVisibility(View.INVISIBLE);
btn_bluetooth.setBackgroundColor(getResources().getColor(R.color.transparent));
}
}
}
protected void createsocket() {
new Thread() {
public void run() {
boolean fail = false;
BluetoothDevice device = myBluetoothAdapter.getRemoteDevice(address1);
try {
BTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
BTSocket.connect();
} catch (IOException e) {
try {
fail = true;
BTSocket.close();
BTHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if (!fail) {
mConnectedThread = new ConnectedThread(BTSocket);
mConnectedThread.start();
BTHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name1)
.sendToTarget();
}
}
}.start();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
return (BluetoothSocket) m.invoke(device, PORT_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
return device.createRfcommSocketToServiceRecord(PORT_UUID);
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if(bytes != 0) {
buffer = new byte[1024];
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
BTHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}
This is how I make the connection, this seems to work properly. Than I use the code underneith to read out the incomming data.
BTHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == MESSAGE_READ) {
String readMessage = " ";
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
inputdata1 = readMessage;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
TextView input1 = findViewById(R.id.input1);
input1.setText(readMessage);
if (readMessage.equals("X")){
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(100);
}
}
}
};
Showing the incomming data in the textview works. But it doesn't recognize the X in the incomming data. I can however see that this data is incomming in the textView and i do send this in de arduino code.
if (fsrReadingHeel >= (fsrReadingHeelOld + 800)){
Serial.println("X");
}
I do know the code is processed because when I say if (!(readMessage.equals("X"))){ than it does vibrate.

Arduinos Serial.print sends in ASCII. When you build a String, you can use ASCII like this: Charset.setName("ASCII") instead of just "UTF-8". This works fine for me (with a Arduino Uno and HC-06 Bluetooth module):
readMessage = new String((byte[]) msg.obj, Charset.setName("ASCII"));
The String you created from the byteBuffer should be limited to the size of the actual data - you could use substring(0, sizeOfData) for that.
When I made my App to connect with my Arduino Uno, I had the problem, that depending on the configuration it ignored the first sent Byte in Android, so try to send a longer string and see if you get something, and that you can actually read it correctly.
I am suggesting that you use Serial.print instead of println, because you don't need the line break in sending. It might also change the message you receive on Android.
if (fsrReadingHeel >= (fsrReadingHeelOld + 800)){
Serial.print("X");
}
You could also use Serial.write instead, but you don't need to - have a look at the differences here: https://arduino.stackexchange.com/questions/10088/what-is-the-difference-between-serial-write-and-serial-print-and-when-are-they

Related

How to separate received digits two by two

I'm working on a project which receives information from an arduino module and shows it as a chart.
The problem is I have 5 elements ( temperature,humidity, etc... ) and the code I have can only receive one number at a time ( for example : 2838752458 ), as you see in the example the number has 10 digits which comes from Arduino and I want to separate them two by two so each two of them goes for one element.
you might ask why I don't set a handler so I can receive each two number at a separated time but I've tried that and it gives me closed application error because the code I have only can receive one number at a time.
public class Analysies extends AppCompatActivity {
Handler h;
String tekrar = "";
String dama = "";
String qaza = "";
String faaliat = "";
String rotobat = "";
private OutputStream outStream = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String address = "00:21:13:00:02:5B";
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private Analysies.ConnectedThread mConnectedThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_analysies);
gifImageView = (GifImageView) findViewById(R.id.gifBro);
txt1 = (GifImageView) findViewById(R.id.afterAutotxt);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
txt1.animate().alpha(1f).setDuration(2000);
}
}, 1000);
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());
sbprint.getBytes().toString();
////////////////////////////// HERE IS WHERE I CAN RECEIVE INFORMATION FROM ARDUINO ///////////////////////////////
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
// Toast.makeText(CommunicationAuto.this, "String:" + sb.toString() , Toast.LENGTH_LONG).show();
break;
}
}
;
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
private 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) {
// Toast.makeText(getApplicationContext(), "Could not Insecure", Toast.LENGTH_SHORT).show();
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
// Toast.makeText(getApplicationContext(), "Socket failed", Toast.LENGTH_SHORT).show();
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
// Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
try {
btSocket.connect();
// Toast.makeText(getApplicationContext(), "Connecting ok!", Toast.LENGTH_SHORT).show();
} 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.
mConnectedThread = new Analysies.ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
try {
btSocket.close();
} catch (IOException e2) {
// errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
Toast.makeText(getApplicationContext(), " Bluetooth is not supported. ", Toast.LENGTH_SHORT).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
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;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
}
}
}
}
The question : How can i separate the 10 digit number two by two and add them to separated integers so i can pass them to the chart activity? Please give me an example for "1234567890" this number.
here is the output of the chart I created so far.
This seems to do what you want:
import java.util.regex.*;
public class HelloWorld{
public static void main(String []args){
String s = "1234567890";
String pattern = "(\\d\\d)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(0));
}
}
}
And output:
12
34
56
78
90
At first make sure the number of your digits (e.g: 1234567890) always divisible by 2. Well, then I have a little hack for you.
First, convert the digits to String and run a for-loop with step 2, then just append the characters at i-th and (i+1)th position into each string producing using the loop into an array. And finally, you can just read item from the array list and send value to your chart just parsing the String into int value to your chart. Here is a sample code I did with Kotlin (but I can convert it into Java code if you need). If you face any issues, feel free to comment.
fun main() {
val digits = 1234567890
val arr = arrayListOf<String>()
for (i in 0 until digits.toString().length step 2) {
val sub = "${digits.toString()[i]}${digits.toString()[i+1]}"
arr.add(sub)
}
println(arr)
}

java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I am want to separate the strings incoming from arduino and store it in variables for database purposes but when I try to divide that string using split() after a few moments the exception occurs
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 and the app keeps stopping
the error is at Line 203 separated[1]
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Android-Arduino";
Button btnOn, btnOff;
TextView temperatureText, heartbeatText;
Handler h;
final int RECIEVE_MESSAGE = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread connectedThread;
// Common service that bluetooth device support
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC address of the bluetooth module.
private static String address = "00:18:E4:35:75:A6";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temperatureText = (TextView) findViewById(R.id.temp);
heartbeatText = (TextView)findViewById(R.id.heartbeat);
getDataArduino();
// Bluetooth adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
// Check whether the bluetooth is enabled / disabled
checkBTState();
}
// Creates the communication chanel
private 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);
}
#Override
public void onResume() {
super.onResume();
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: "
+ e.getMessage() + ".");
}
btAdapter.cancelDiscovery();
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException ex) {
errorExit("Fatal Error", "In onResume() and unable to close socket during " +
"connection failure" + ex.getMessage() + ".");
}
}
// Creates the data stream with the server
connectedThread = new ConnectedThread(btSocket);
connectedThread.start();
}
#Override
public void onPause() {
super.onPause();
try {
btSocket.close();
} catch (IOException ex) {
errorExit("Fatal Error", "In onPause() and failed to close socket." +
ex.getMessage() + ".");
}
}
private void checkBTState() {
// Checks if the devices has bluetooth functionalities
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
// Checks if the bluetooth is on
if (btAdapter.isEnabled()) {
} else {
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
// Get number of bytes and message in "buffer"
bytes = mmInStream.read(buffer);
// Send to message queue Handler
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(String message) {
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
public void getDataArduino() {
temperatureText.clearComposingText();
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
String[] separated = sbprint.split(":");
heartbeatText.setText(separated[0]+ "");
temperatureText.setText(separated[1]+ "");
}
Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
}
};
}
}
I need the temperature to display differently and heartrate to be displayed individually.
You can first try to print the input data (StringBuffer sb) and split String array(String[] separated). You are getting error because the Strings have not split as your expected and only 1 element is present in the array sbprint, this is why when you try to access the second element you get ArrayIndexOutofBound index.
Once you print the Split String Array it would give you an idea where your data is wrong.

I am trying to send data via bluetooth but Serial.available() always return 0

I have created an android app that (theoretically) sends data to the arduino via bluetooth.
I know that I have managed to get connectivity(the led on the bluetooth module stopped blinking) but the Serial.available() isn't changing when I write some values.
I have tried using different apps (from the play store) - no luck.
The arduino code which suppose to read the data:
void setup() {
Serial.begin(9600);
Serial.println("Simple Motor Shield sketch");
}
void loop() {
if(Serial.available()>0){
Serial.println("in");
for(int i=0;i<=2;i++){
joystick[i] = Serial.read();
}
for(int i=0;i<=2;i++){
Serial.println(joystick[i]);
}
delay(1);
}
}
joystick[] is an int array
android code:
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
int dataLength = dataInPrint.length(); //get length of data received
recDataString.delete(0, recDataString.length()); //clear all string data
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnLeft.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnRight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
layout_joystick.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
js.drawStick(arg1);
if (arg1.getAction() == MotionEvent.ACTION_DOWN
|| arg1.getAction() == MotionEvent.ACTION_MOVE) {
//int x = js.getX();
//int y = js.getY();
int angle = (int)js.getAngle();
int distance = (int)js.getDistance();
int maxDist = js.getOffset()+js.getLayoutHeight();
distance =(int)(distance/(maxDist/9));
angle=(int)(angle/40);
distance=Math.max(distance,-9);
distance=Math.min(distance,9);
angle=Math.max(angle,-9);
angle=Math.min(angle,9);
//mConnectedThread.write(String.valueOf(x));
//mConnectedThread.write(String.valueOf(y));
mConnectedThread.write(String.valueOf(angle));
mConnectedThread.write(String.valueOf(distance));
Log.i("Bluetooth","Distance: " + distance);
Log.i("Bluetooth","Angle: " + angle);
}
return true;
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("0");
}
#Override
public void onPause()
{
super.onPause();
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
I think you have connected Bluetooth module on serial RX,TX pins of arduino board. this is not the case. You need to use separate serial for communication with Bluetooth. You can use software serial for this purpose otherwise Bluetooth module won't work.
The reason behind this is that the arduino uses same serial pins to communicate with PC (Serial terminal and program load) so it cannot simultaneously send data to Bluetooth.
Have a look at here: https://bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/
Sorry for the unclarity, basically what I wanted to do is to check if I had any data available on the bluetooth serial connection.
So I hoped that Serial.available() would be more than 0 when I sent data.Yet, the Serial.available() and Serial.Read() didn't seemed to work when I sent data.
* I have managed to solve the problem using the program from: http://www.circuitmagic.com/arduino/arduino-and-bluetooth-hc-06-to-control-the-led-with-android-device/ *

Print a complete graphical layout from a tablet which has inbuilt printer android

I have an android tablet in which inbuilt printer and scanner are present.
Now my task is to print a gate pass. Gate pass layout contains many text fields and edit text. I need my tablets printer to print this whole page.I need the code in java.
I would like to know if printing can be done directly without any PDF or Bluetooth. Because I can print only a single field using the print button as I have all the sdk regarding that printer. Now, my issue is that I want to print the whole layout.
try this code hope it help you
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
findBT();
openBT();
} catch (IOException ex) {
ex.printStackTrace();
}
}});
Find BT Method
// this will find a bluetooth printer device
void findBT() {try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null) {
myLabel.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// RPP300 is the name of the bluetooth printer device
// we got this name from the list of paired devices
if (device.getName().equals("RPP300")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth device found.");
}catch(Exception e){
e.printStackTrace();
}}
Open BT method
// tries to open a connection to the bluetooth printer device
void openBT() throws IOException {
try {// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (Exception e) {
e.printStackTrace();
}}
We need beginListenForData() method so that openBT() method will work.
after opening a connection to bluetooth printer device,
we have to listen and check if a data were sent to be printed.
void beginListenForData() {
try {final Handler handler = new Handler();
// this is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(
readBuffer, 0,
encodedBytes, 0,
encodedBytes.length
);
// specify US-ASCII encoding
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
// tell the user data were sent to bluetooth printer device
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (Exception e) {
e.printStackTrace();
}}
We will make an onClickListener for the “Send” button. Put the following code after the onClickListener of the “Open” button, inside onCreate() method.
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
ex.printStackTrace();
}
}});
sendData() method is needed so that the “Open” button will work. Put it below the beginListenForData() method code block.
// this will send text data to be printed by the bluetooth printer
void sendData() throws IOException {try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data sent.");
} catch (Exception e) {
e.printStackTrace();
}}
We will code an onClickListener for the “close” button so we can close the connection to Bluetooth printer and save battery. Put the following code after the onClickListener of the “Send” button, inside onCreate() method.
// close bluetooth connection
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
closeBT();
} catch (IOException ex) {
ex.printStackTrace();
}
}});
closeBT() method in Step 12 will not work without the following code. Put it below the sendData() method code block.
// close the connection to bluetooth printer.
void closeBT() throws IOException {
try {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
} catch (Exception e) {
e.printStackTrace();
}}
Make sure the BLUETOOTH permission was added to your manifest file. It is located in manifests/AndroidManifest.xml, the code inside should look like the following.
<uses-permission android:name="android.permission.BLUETOOTH" />

Prompted for Bluetooth PIN when connecting to already paired device on Android

I am developing an Android app to connect to a simple device that supports the bluetooth serial port profile (SPP). I am able to successfully connect and exchange data, but each time I connect the user is prompted to enter the PIN for the device.
In the bluetooth settings I can see that the device is 'paired by not connected'.
The prompt is an issue because if the user is not quick enough in entering the PIN, the socket connect times out and the user must try again.
Relevant bits of code below...
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.scanlayout);
...
_Context = this;
_ActivityCreated = true;
_ReceivedText = (TextView)findViewById(R.id._Scan_Results);
_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
_BluetoothDevice = _BluetoothAdapter.getRemoteDevice(_DeviceAddress);
_BusySpinner = ProgressDialog.show(_Context, "", "Connecting to scanner...");
new ConnectToScannerTask().execute(_BluetoothDevice);
}
private final Handler scanReceivedHandler = new Handler()
{
#Override
public void handleMessage(Message message)
{
String receivedText = (String)message.obj;
_ReceivedText.setText(receivedText);
}
};
private class ConnectToScannerTask extends AsyncTask<BluetoothDevice, Void, InputStream>
{
#Override
protected InputStream doInBackground(BluetoothDevice... params)
{
BluetoothDevice device = params[0];
try
{
_Socket = device.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
_BluetoothAdapter.cancelDiscovery();
_Socket.connect();
return _Socket.getInputStream();
}
catch (IOException e)
{
Log.d("ScanActivity.ConnectToScannerTask.doInBackground", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(final InputStream result)
{
_BusySpinner.dismiss();
if (result == null)
{
_ReceivedText.setText("Failed to connect to scanner.");
return;
}
Thread thread = new Thread()
{
#Override
public void run()
{
byte[] buffer = new byte[1024];
try
{
while (_ActivityCreated)
{
Arrays.fill(buffer, (byte) 0);
int bytesRead = result.read(buffer);
if (bytesRead > 0)
{
Message message = scanReceivedHandler.obtainMessage(1, new String(buffer));
message.sendToTarget();
Log.e("ScanActivity", "Received: " + new String(buffer));
}
if (bytesRead < 0)
{
break;
}
}
Message message = scanReceivedHandler.obtainMessage(1, "End of Stream");
message.sendToTarget();
Log.e("ScanActivity", "End of Stream");
}
catch (Exception e)
{
Message message = scanReceivedHandler.obtainMessage(1, "Connection to scanner lost");
message.sendToTarget();
Log.e("ScanActivity", e.getMessage());
}
try
{
_Socket.close();
}
catch (IOException e)
{
Log.e("ScanActivity", e.getMessage());
}
}
};
thread.start();
}
}
As long as the user is quick about entering the PIN, the connect succeeds and I can receive data. My hunch is that I am missing a setup step. I'm not that familiar with the specifics of BT, though, so I am not sure if this might be an issue where the device is forcing the PIN to be entered?
This might be a problem with the remote device that does not keep the device bonded, (meaning storing the link key to be used in subsequent connect) that will result in re-pairing each time and requiring the PIN to be entered.
Android should typically store the bonding information once it has paired successfully.

Categories

Resources