Send data to bluetooth printer - android

I am using SimpleBluetoothLibrary to access my bluetooth printer.now i can search available devices,select bluetooth printer from the list,connect to the printer.those parts are done.but i don't know how to send data to the printer for print job.this is onDeviceConnected method.i've got device address from it.but i want to send data to printer.
#Override
public void onDeviceConnected(BluetoothDevice device) {
//a device is connected so you can now send stuff to it
mTxt.setText("Connection Status:Connected:" + device.getAddress());
Log.d("Mac_Address", device.getAddress());
}

There is a simple example for sending data from Bluetooth.I hope it helps you.
MainActivity.java
package com.example.bluetoothprinter;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
// will show the statuses
TextView myLabel;
// will enable user to enter any text to be printed
EditText myTextbox;
// android built in classes for bluetooth operations
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// we are goin to have three buttons for specific functions
Button openButton = (Button) findViewById(R.id.open);
Button sendButton = (Button) findViewById(R.id.send);
Button closeButton = (Button) findViewById(R.id.close);
myLabel = (TextView) findViewById(R.id.label);
myTextbox = (EditText) findViewById(R.id.entry);
// open bluetooth connection
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
findBT();
openBT();
} catch (IOException ex) {
}
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
// close bluetooth connection
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
closeBT();
} catch (IOException ex) {
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// 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) {
// MP300 is the name of the bluetooth printer device
if (device.getName().equals("MP300")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// 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 (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// 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);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send 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 (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Close the connection to bluetooth printer.
void closeBT() throws IOException {
try {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:" />
<EditText
android:id="#+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/label"
android:background="#android:drawable/editbox_background" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#id/entry"
android:layout_marginLeft="10dip"
android:text="Open" />
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/open"
android:layout_toLeftOf="#id/open"
android:text="Send" />
<Button
android:id="#+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/send"
android:layout_toLeftOf="#id/send"
android:text="Close" />
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothprinter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<supports-screens android:anyDensity="true" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Result pictures are below:

Related

Bluetooth send a text to other device

i have a simple question:
first, this is all my code:
package com.example.mybluetoothapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
BroadcastReceiver broadcastReceiver;
BluetoothAdapter bluetoothAdapter;
public UUID serverUuid = UUID.fromString("SERVEUR");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Votre appareil n'a pas de Bluetooth",
Toast.LENGTH_LONG).show();
finish();
}
if (!bluetoothAdapter.isEnabled()) {
Intent bluetoothIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bluetoothIntent, 1);
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice bluetoothDevice : pairedDevices) {
devices.add(bluetoothDevice);
}
}
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
Intent dicoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dicoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(dicoverableIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onDestroy() {
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
private class AcceptThread extends Thread {
BluetoothServerSocket bluetoothServerSocket;
public AcceptThread() {
BluetoothServerSocket serverSocketTmp = null;
try {
serverSocketTmp = bluetoothAdapter
.listenUsingRfcommWithServiceRecord("Bluetooth APP",
serverUuid);
bluetoothServerSocket = serverSocketTmp;
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
socket = bluetoothServerSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
if (socket != null) {
// TODO: Managed Connection
// TODO: Envoyer Bonjour et Bienvenue
try {
bluetoothServerSocket.close();
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
super.run();
}
private void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class ConnectThread extends Thread {
BluetoothSocket socket;
BluetoothDevice device;
public ConnectThread(BluetoothDevice device) {
this.device = device;
BluetoothSocket socketTmp = null;
try {
socketTmp = device
.createRfcommSocketToServiceRecord(serverUuid);
socket = socketTmp;
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
bluetoothAdapter.cancelDiscovery();
try {
socket.connect();
} catch (IOException e) {
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
return;
}
// TODO: Manage connection
super.run();
}
private void cancel() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ConnectedThread extends Thread {
private BluetoothSocket bluetoothSocket;
InputStream inputStream = null;
OutputStream outputStream = null;
public ConnectedThread(BluetoothSocket socket) {
bluetoothSocket = socket;
InputStream inputStreamTmp = null;
OutputStream outputStreamTmp = null;
try {
inputStreamTmp = bluetoothSocket.getInputStream();
outputStreamTmp = bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = inputStreamTmp;
outputStream = outputStreamTmp;
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
// TODO: Envoyer message à l'affichage
} catch (IOException e) {
e.printStackTrace();
break;
}
}
super.run();
}
public void write(byte[] bytes) {
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i get this code from a website, so please how i can us it to send a 'hello world' bettween two smartphone ?
please i need help
thank you
Use the ConnectedThread:
How to send any data.
//Code to send text
String text = "Example";
mConnectedThread.write(text.getBytes());
How to receive the sent text (array length is 1024 and 1024 bytes is 1 KB), modify the run() method in ConnectedThread
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
//Received text is here
String text = new String(buffer, 0, bytes);
Log.d(TAG, text);
} catch (IOException e) {
e.printStackTrace();
break;
}
}
super.run();
}
After checking your code, it seems the threads haven't been started

Transfer file between 2 android device

I want to transfer a file between two devices, a server and a client .. I have a little problem on the client side.
I got this error in logcat:
java.lang.ArrayIndexOutOfBoundsException: length=1024; regionStart=0; regionLength=-1
please if my codes are wrong tell me. I want to make an app and its 4 days i am working on transfering. it get to me awful. please help
this is the client:
package com.example.test;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
import android.os.Environment;
public class MainActivity extends ActionBarActivity {
EditText editTextAddress;
Button buttonConnect;
TextView textPort;
static final int SocketServerPORT = 8000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.address);
textPort = (TextView) findViewById(R.id.port);
textPort.setText("port: " + SocketServerPORT);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
ClientRxThread clientRxThread =
new ClientRxThread(
editTextAddress.getText().toString(),
SocketServerPORT);
clientRxThread.start();
}});
}
private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
File file = new File(
Environment.getExternalStorageDirectory(),
"input.jpg");
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
socket.close();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
"Finished",
Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eMsg,
Toast.LENGTH_LONG).show();
}});
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
client xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.androidsocketfiletransferclient.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="File Transfer Client"
android:textStyle="bold" />
<EditText
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dstAddress" />
<TextView
android:id="#+id/port"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connect..." />
client manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
server :
package com.example.testserverandroid;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
TextView infoIp, infoPort;
static final int SocketServerPORT = 8000;
ServerSocket serverSocket;
ServerSocketThread serverSocketThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
infoIp.setText(getIpAddress());
serverSocketThread = new ServerSocketThread();
serverSocketThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public class ServerSocketThread extends Thread {
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
FileTxThread fileTxThread = new FileTxThread(socket);
fileTxThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class FileTxThread extends Thread {
Socket socket;
FileTxThread(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory(),
"test.txt");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
os.write(bytes, 0, bytes.length);
os.flush();
socket.close();
final String sentMsg = "File sent to: "
+ socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, sentMsg,
Toast.LENGTH_LONG).show();
}
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
server manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
In your client, when you are reading from the input stream, the number of bytes read will be -1 if you are already at the end of the stream. This is described in the documentation for InputStream.
The ArrayIndexOutOfBoundsException exception occurs when this statement executes and bytesRead is -1.
bos.write(bytes, 0, bytesRead);
You need to restructure your client code that reads the input stream to check for end-of-stream.
Replace this:
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
With this:
int bytesRead;
while ((bytesRead = is.read(bytes)) > 0) {
bos.write(bytes, 0, bytesRead);
}

Connecting arduino to android using wifi Shield

I am trying to connect arduino Uno to android device using Wifi over a Common Lan connection but the following code is not giving me any response from Arduino. Arduino is working well with the desktop checking code.Here is my android part of the code on click of a toggle button
//WIFI socket code
ToggleButton toggle = (ToggleButton) findViewById(R.id.wifiTButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// wifi thread code
final Runnable r = new Runnable()
{
public void run()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
textOut = (TextView) findViewById(R.id.textOut);
textIn=(EditText) findViewById(R.id.textIn);
try {
socket = new Socket("10.0.0.101", 7);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeByte(111111);
//dataOutputStream.writeUTF("111111".toString() );//textOut.getText().toString());
textIn.setText(dataInputStream.readByte());
// textIn.setText(dataInputStream.readUTF());
Log.d(TAG, " why is not working");
} catch (UnknownHostException e) {
Log.d(TAG, "Unknown Host");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "Input Output Exception");
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
}
}
});
I was able to solve the problem. It is running well with the command button instead of a toggle button and properly using the thread syntax.
Here is a sample application mainActivity code.
package com.example.arduinoandroid;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Handler handler;
String TAG = "main Activity";
Button bt1;
TextView textOut;
EditText editIn;
static byte abc;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
class Task implements Runnable {
#Override
public void run() {
try {
socket = new Socket("10.0.0.101", 7);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeByte(111);
// dataOutputStream.writeUTF("111111".toString()
// );//textOut.getText().toString());
abc = dataInputStream.readByte();
Toast.makeText(getBaseContext(), abc, Toast.LENGTH_SHORT)
.show();
// textIn.setText(dataInputStream.readUTF());
Log.d(TAG, " why is not working");
} catch (UnknownHostException e) {
Log.d(TAG, "Unknown Host");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "Input Output Exception");
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textOut.setText("working ae");
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
// WIFI socket code
bt1 = (Button) findViewById(R.id.chkButton1);
textOut = (TextView) findViewById(R.id.textOut);
editIn = (EditText) findViewById(R.id.editIn);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Task()).start();
}
});
}
}
and the code for xml part is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="#+id/chkButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="140dp"
android:text="Check wifi" />
<TextView
android:id="#+id/textOut"
android:layout_width="wrap_content"
android:layout_height="39dp"
android:layout_gravity="bottom|right"
android:text="Output" />
<EditText
android:id="#+id/editIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:text="111111"/>
</LinearLayout>
Please include the following permissions in the manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Android App to print from a bluetooth printer

The app I have found online works flawlessly except when clicking onto the Send Button, after typing something into the textbox, the printer runs, and stops in the middle of the process of printing, program doesn't crash however. I'm just curious if I'm using the wrong UUID, in fact I don't even know what it is. I have this following class, which is the only class needed to run the app, the rest are XML, with all three bluetooth permissions;
package com.example.bluetoothprinter;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
// will show the statuses
TextView myLabel;
// will enable user to enter any text to be printed
EditText myTextbox;
// android built in classes for bluetooth operations
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// we are goin to have three buttons for specific functions
Button openButton = (Button) findViewById(R.id.open);
Button sendButton = (Button) findViewById(R.id.send);
Button closeButton = (Button) findViewById(R.id.close);
myLabel = (TextView) findViewById(R.id.label);
myTextbox = (EditText) findViewById(R.id.entry);
// open bluetooth connection
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
findBT();
openBT();
} catch (IOException ex) {
}
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
// close bluetooth connection
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
closeBT();
} catch (IOException ex) {
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 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) {
// OJL411MY29I911JH is the name of the bluetooth printer device shown after scan
if (device.getName().equals("OJL411MY29I911JH")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 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 (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 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);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send 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 (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Close the connection to bluetooth printer.
*/
void closeBT() throws IOException {
try {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I added code to run closeBT function at the end of the sendData function. if you don't close the connection, I think it is hanging in the process of sending.
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 (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

Android Bluetooth reading btrs232 adapter

I am writing a simple communication program between Android device 2.2 and Bluetooth RS232 adapter.
I managed to connect and send text successfully, but when reading from the adapter the application crashes.
I do appreciate any help and advice.
Thanks
main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/text_messages"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:text="Button" android:id="#+id/button_listen"
android:layout_width="wrap_content" android:layout_height="wrap_content">
</Button>
</LinearLayout>
MyActivity.java
package com.epostech.bt232test;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
//import android.widget.ArrayAdapter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MyActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 3;
private String mac = "";
private static final UUID MY_UUID_INSECURE = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket clientSocket;
// private ArrayAdapter<String> mArrayAdapter;
private Vector<String> deviceMacs = new Vector<String>();
private Vector<String> deviceNames = new Vector<String>();
#SuppressWarnings("unused")
private Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TextView messageText = (TextView) findViewById(R.id.text_messages);
// messageText.setVisibility(View.VISIBLE);
setContentView(R.layout.main);
Button listenButton = (Button) findViewById(R.id.button_listen);
listenButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// closeSocket();
sendMessage(clientSocket, "P\r\n");
// testing(mac);
}
});
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
String toastText = "";
/*
* if(bluetooth.isEnabled()){ String address= bluetooth.getAddress();
* String name=bluetooth.getName(); toastText=name+" : "+address;
*
* } else
*/
if (!bluetooth.isEnabled()) {
toastText = "Bluetooth is not Enabled!";
Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(this, "BlueTooth Enabled", Toast.LENGTH_LONG).show();
}
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
// Toast.makeText(this,"Size="+pairedDevices.size(),
// Toast.LENGTH_LONG).show();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a
// ListView
deviceMacs.add(device.getAddress());
deviceNames.add(device.getName());
}
} else {
Toast.makeText(this, "Size=" + pairedDevices.size(),
Toast.LENGTH_LONG).show();
}
mac = deviceMacs.get(deviceNames.indexOf("M7705B0125"));
BluetoothDevice device = bluetooth.getRemoteDevice(mac);
try {
clientSocket = device
.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
clientSocket.connect();
// TODO Transfer data using the Bluetooth Socket
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
BluetoothSocketListener bsl = new BluetoothSocketListener(clientSocket, handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendMessage(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = msg.getBytes();
byteString[byteString.length - 1] = 0;
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
// The Handler that gets information back from the BluetoothChatService
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeSocket();
}
}
BluetoothSocketListener.java
package com.epostech.bt232test;
import java.io.IOException;
import java.io.InputStream;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket,
Handler handler, TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
InputStream instream=null;
try {
instream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String message = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = instream.read(buffer);
message = message + new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity
handler.post(new MessagePoster(textView, message));
} catch (IOException e) {
break;
}
}
}
/*
public void run() {
int bufferSize = 256;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead==bufferSize)&&(buffer[bufferSize-1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(textView, message));
//socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
*/
}
MessagePoster.java
package com.epostech.bt232test;
import android.widget.TextView;
public class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
Problem solved
I can read and write to RS232 and display the result on TextView using Handler to communicate with UI and Socket thread.
It was hard excersise but I did it with simple program as follows:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// messageText.setVisibility(View.VISIBLE);
setContentView(R.layout.main);
messageText = (TextView) findViewById(R.id.text_messages);
Button listenButton = (Button) findViewById(R.id.button_listen);
listenButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// closeSocket();
sendData(clientSocket, "P\r\n");
}
});
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
String toastText = "";
/*
* if(bluetooth.isEnabled()){ String address= bluetooth.getAddress();
* String name=bluetooth.getName(); toastText=name+" : "+address;
*
* } else
*/
if (!bluetooth.isEnabled()) {
toastText = "Bluetooth is not Enabled!";
Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(this, "BlueTooth Enabled", Toast.LENGTH_LONG).show();
}
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
// Toast.makeText(this,"Size="+pairedDevices.size(),
// Toast.LENGTH_LONG).show();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a
// ListView
deviceMacs.add(device.getAddress());
deviceNames.add(device.getName());
}
} else {
Toast.makeText(this, "Size=" + pairedDevices.size(),
Toast.LENGTH_LONG).show();
}
mac = deviceMacs.get(deviceNames.indexOf("M7705B0125"));
BluetoothDevice device = bluetooth.getRemoteDevice(mac);
try {
clientSocket = device
.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
clientSocket.connect();
// TODO Transfer data using the Bluetooth Socket
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
BluetoothSocketListener bsl = new BluetoothSocketListener(clientSocket,
handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}// end of onCreate()code
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
messageText.setText(readMessage);
}
};
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// The Handler that gets information back from the BluetoothChatService
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeSocket();
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
private InputStream inStream;
private OutputStream outStream;
public BluetoothSocketListener(BluetoothSocket socket, Handler handler,
TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
try {
outStream = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int data;
try {
inStream = socket.getInputStream();
int bytesRead = -1;
String message = "";
// Keep listening to the InputStream while connected
int len= 0;
while (true) {
try {
// Read from the InputStream
bytesRead = inStream.read(buffer);
message= message+new String(buffer,0,bytesRead);
// Send the obtained bytes to the UI Activity
byte[] byteString = message .getBytes();
byteString[byteString.length - 1] = 0;
outStream.write(byteString);
handler.post(new MessagePoster(textView,"Text="+ message+" "+"Bytes read="+bytesRead));
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
private void sendData(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = msg.getBytes();
//byteString[byteString.length - 1] = 0;
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
Dont forget to add the permission to the manifest
<uses-permission
android:name="android.permission.BLUETOOTH" />
I discovered one thing using a serial to BT adapter hooked to a microcontroler.
Often, the data sent to the serial port is a string ended by [].
I used a serial to bluetooth adapter ine one of my projects, sending data lines ended by a and found that handling data with a Scanner rather than a standard buffer really works better.
Example of the Bluetooth Chat modified:
Scanner scan = new Scanner(new InputStreamReader(mmInStream));
String line;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
//Send the obtained bytes to the UI Activity
line = scan.next();
mHandler.obtainMessage(CalibrationS2PActivity.MESSAGE_READ, line.length(), -1, line).sendToTarget();
} catch (Exception e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}

Categories

Resources