I have a Bluetooth service in my project and i connect all fragment but i cant send message with Connected Thread. it does not work correctly. Where is my false ? I am looking for solution since 3 days I can not find any solution.
Why i cant send any message. My log return:
BluetoothConnectionService.write(byte[])' on a null object reference
i know ConnectedThread empty but why it is empty ?
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// ObjectInputStream tmpObjIn = null;
//ObjectOutputStream tmpObjOut = null;
if(socket!=null)
{
Log.d(TAG, "ConnectedThread: Socket not empty");
}
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
}catch (NullPointerException e){
e.printStackTrace();
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
//tmpObjOut = new ObjectOutputStream(tmpOut);
//tmpObjOut.flush();
//tmpObjIn = new ObjectInputStream(tmpIn);
} catch (IOException e) {
Log.d(TAG, "ConnectedThread: doest work OUTPUT");
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
// mObjectOutStream = tmpObjOut;
// mObjectInStream = tmpObjIn;
}
This is all service.java code:
package com.example.duygu.mybluetoothdevicelist;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.UUID;
public class BluetoothConnectionService {
private static final String TAG = "BluetoothConnectionServ";
private static final String appName = "MYAPP";
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private final BluetoothAdapter mBluetoothAdapter;
Context mContext;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mmDevice;
private UUID deviceUUID;
ProgressDialog mProgressDialog;
private BluetoothSocket mmSocket;
private ConnectedThread mConnectedThread;
public BluetoothConnectionService(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try{
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);
Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, "run: RFCOM server socket start.....");
socket = mmServerSocket.accept();
Log.d(TAG, "run: RFCOM server socket accepted connection.");
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
//talk about this is in the 3rd
if(socket != null){
connected(socket,mmDevice);
}
Log.i(TAG, "END mAcceptThread ");
}
public void cancel() {
Log.d(TAG, "cancel: Canceling AcceptThread.");
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
}
}
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
}
//will talk about this in the 3rd video
connected(mmSocket,mmDevice);
}
public void cancel() {
try {
Log.d(TAG, "cancel: Closing Client Socket.");
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
}
}
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void start() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
/**
AcceptThread starts and sits waiting for a connection.
Then ConnectThread starts and attempts to make a connection with the other devices AcceptThread.
**/
public void startClient(BluetoothDevice device,UUID uuid){
Log.d(TAG, "startClient: Started.");
//initprogress dialog
mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
,"Please Wait...",true);
mConnectThread = new ConnectThread(device, uuid);
mConnectThread.start();
}
/**
Finally the ConnectedThread which is responsible for maintaining the BTConnection, Sending the data, and
receiving incoming data through input/output streams respectively.
**/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//private final ObjectInputStream mObjectInStream;
// private final ObjectOutputStream mObjectOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// ObjectInputStream tmpObjIn = null;
//ObjectOutputStream tmpObjOut = null;
if(socket!=null)
{
Log.d(TAG, "ConnectedThread: Socket not empty");
}
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
}catch (NullPointerException e){
e.printStackTrace();
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
//tmpObjOut = new ObjectOutputStream(tmpOut);
//tmpObjOut.flush();
//tmpObjIn = new ObjectInputStream(tmpIn);
} catch (IOException e) {
Log.d(TAG, "ConnectedThread: doest work OUTPUT");
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
// mObjectOutStream = tmpObjOut;
// mObjectInStream = tmpObjIn;
}
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) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
Intent incomingMessageIntent = new Intent("incomingMessage");
incomingMessageIntent.putExtra("theMessage", incomingMessage);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(incomingMessageIntent);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
Log.d(TAG, "connected: Starting.");
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
/**
* Write to the ConnectedThread in an unsynchronized manner
*
* #param out The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) { //changed this
// Create temporary object
ConnectedThread r;
r=mConnectedThread;
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
r.write(out);
}
}
I found the solution. If you use fragment, you can do just receive message but you can not send message. If you want to send message you have to use MainActivity.java If you want to getting value on the fragment you use this type:
*Creating method on MainActivty.java (That is send message with mBluetoothService.write(bytes) use the parameters)
*On the fragment side, you have to write method what you want to send. And you have to send method to MainActivity.java
I am working on the for 5 days and finally i found the solution.
Related
I did debug on my project and my 3. fragment cant connect Bluetooth service. That include send message to other devices. My connection is starting 1st fragment my device id and device name should keep bluetooth service but i connect with below code my connection null and ConnectedThread return null object. So how can i connect bluetooth service java in my fragment again ?
I am calling this line on my Fragment
mBluetoothConnection = new BluetoothConnectionService(getActivity().getApplicationContext());
And write function in BluetoothService.java:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
byte[] bytes = editText.getText().toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
})
My breakpoint on mBluetoothConnection.write(bytes); this line and every ConnectedThread, outputstream return null and why ?
And this is my service:
public class BluetoothConnectionService {
private static final String TAG = "BluetoothConnectionServ";
private static final String appName = "MYAPP";
private static final UUID MY_UUID_INSECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final BluetoothAdapter mBluetoothAdapter;
Context mContext;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mmDevice;
private UUID deviceUUID;
ProgressDialog mProgressDialog;
private ConnectedThread mConnectedThread;
public BluetoothConnectionService(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try{
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);
Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, "run: RFCOM server socket start.....");
if(socket == null)
socket = mmServerSocket.accept();
Log.d(TAG, "run: RFCOM server socket accepted connection.");
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
//talk about this is in the 3rd
if(socket != null){
Log.d(TAG, "run: Connected is active");
connected(socket,mmDevice);
}
Log.i(TAG, "END mAcceptThread ");
}
public void cancel() {
Log.d(TAG, "cancel: Canceling AcceptThread.");
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
}
}
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
}
//will talk about this in the 3rd video
connected(mmSocket,mmDevice);
}
public void cancel() {
try {
Log.d(TAG, "cancel: Closing Client Socket.");
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
}
}
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void start() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
/**
AcceptThread starts and sits waiting for a connection.
Then ConnectThread starts and attempts to make a connection with the other devices AcceptThread.
**/
public void startClient(BluetoothDevice device,UUID uuid){
Log.d(TAG, "startClient: Started.");
//initprogress dialog
mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
,"Please Wait...",true);
mConnectThread = new ConnectThread(device, uuid);
mConnectThread.start();
}
/**
Finally the ConnectedThread which is responsible for maintaining the BTConnection, Sending the data, and
receiving incoming data through input/output streams respectively.
**/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
}catch (NullPointerException e){
e.printStackTrace();
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
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) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
Intent incomingMessageIntent = new Intent("incomingMessage");
incomingMessageIntent.putExtra("theMessage", incomingMessage);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(incomingMessageIntent);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
Log.d(TAG, "connected: Starting.");
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
/**
* Write to the ConnectedThread in an unsynchronized manner
*
* #param out The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
if(mConnectedThread==null){
return;
}
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
mConnectedThread.write(out);
}
}
;
In my application that in the beginning i only manage a single Activity for connect and exchange data with OBD2 via bluetooth i add a navigation drawer and more tasks that some of them still use bluetooth connection.
For not to weigh bluetooth for each Fragment i close the Socket connection and delete the instantiation of the class MyBluetoothService.java posted below:
public class MyBluetoothService {
// Debugging
private static final String TAG = "MyBluetoothService";
// Unique UUID for this application
private static final UUID MY_UUID_SECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
//Threads
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private ManageDataThread mManageThread;
//States UI
private int mState;
private int mNewState;
//Readed Data, raw and formatted
private String rawData = null;
private String formattedMessage = null;
//Stopper for the write array and w8 response
private boolean canGo = true;
private ArrayList<String> commandArray = null;
//private BluetoothSocket mmSocket = null;
//private BluetoothDevice mmDevice = null;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
public static final int STATE_WAIT_RESPONSE = 4; //now wait the response of message send
public static final int STATE_NO_MSG_SEND = 5; //now don't wait for responce
/**
* Constructor. Prepares a new BluetoothChat session.
*
* #param context The UI Activity Context
* #param handler A Handler to send messages back to the UI Activity
*/
public MyBluetoothService(Context context, Handler handler, ArrayList<String> commands) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mNewState = mState;
mHandler = handler;
//TODO gestire i comandi direttamente da questa classe con uno sharedArray
commandArray = commands;
}
/**
* Update UI title according to the current state of the chat connection
*/
private synchronized void updateUserInterfaceTitle() {
mState = getState();
Log.d(TAG, "updateUserInterfaceTitle() " + mNewState + " -> " + mState);
mNewState = mState;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(Constants.MESSAGE_STATE_CHANGE, mNewState, -1).sendToTarget();
}
/**
* Return the current connection state.
*/
public synchronized int getState() {
return mState;
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
*
* #param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Cancel any thread currently managing connections
if (mManageThread != null) {
mManageThread.cancel();
mManageThread = null;
}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
// Update UI title
updateUserInterfaceTitle();
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
*
* #param socket The BluetoothSocket on which the connection was made
* #param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
device) {
Log.d(TAG, "manage, Socket Type:");
// Cancel the thread that completed the connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Constants.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
// Update UI title
updateUserInterfaceTitle();
}
private synchronized void manage(BluetoothSocket socket, BluetoothDevice device) {
Log.d(TAG, "Manage Socket");
// Cancel the thread that completed the connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Cancel any thread currently managing connections
if (mManageThread != null) {
mManageThread.cancel();
mManageThread = null;
}
canGo = true;
// Start the thread to manage the connection and perform transmissions
mManageThread = new ManageDataThread(socket);
mManageThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Constants.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
// Update UI title
updateUserInterfaceTitle();
}
/**
* Stop all threads
*/
public synchronized void stop() {
Log.d(TAG, "stop");
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mManageThread != null) {
canGo = false;
mManageThread.cancel();
mManageThread = null;
}
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
}
/**
* Write to the ConnectedThread in an unsynchronized manner
*
* #param out The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
// Start the service over to restart listening mode
MyBluetoothService.this.stop();
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
// Start the service over to restart listening mode
//MyBluetoothService.this.start();
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} catch (IOException e) {
Log.e(TAG, "Socket Type: create() failed", e);
}
mmSocket = tmp;
mState = STATE_CONNECTING;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
connectionFailed();
return;
}
// Reset the ConnectThread because we're done
synchronized (MyBluetoothService.this) {
mConnectThread = null;
}
// Start the connected thread
//connected(mmSocket, mmDevice);
manage(mmSocket, mmDevice);
Log.d(TAG, "mmSocket: " + mmSocket);
Log.d(TAG, "mmDevice: " + mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread: ");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
mState = STATE_CONNECTED;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (mState == STATE_CONNECTED) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
//TODO devo gestire l'arrivo di bytes
ObdCommand obc = new ObdCommand();
obc.readResult(mmInStream);
formattedMessage = obc.getResult();
//buffer = (byte) obc.getBuffer();
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, formattedMessage)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
*
* #param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
if (mmInStream != null){
try {
mmInStream.close();
} catch (Exception e) {
Log.e(TAG, "close() of InStream socket failed", e);
}
}
if (mmOutStream != null){
try {
mmOutStream.close();
} catch (Exception e) {
Log.e(TAG, "close() of OutStream socket failed", e);
}
}
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
/** Thread che controlla la connessione e lo scambio continuo di messaggi con il
* dispositivo OBD connesso ...
*/
//TODO
public class ManageDataThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean wait_response = false;
private String typeCommand;
public ManageDataThread(BluetoothSocket socket) {
Log.d(TAG, "create ManageDataThread: ");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
mState = STATE_CONNECTED;
}
public void run() {
ObdCommand obc = new ObdCommand();
while(canGo) {
for (final String command : commandArray) {
byte[] send = command.getBytes();
write(send); //Setta la wait_response come true
//mState = STATE_WAIT_RESPONSE;
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (wait_response) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
obc.readResult(mmInStream);
//formattedMessage = obc.getResult();
formattedMessage = obc.getCalculatedResult();
//Ritorno la ripologia di comando
typeCommand = obc.getCommandType();
//buffer = (byte) obc.getBuffer();
// Send the obtained bytes to the UI Activity
/*mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, formattedMessage)
.sendToTarget();*/
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, typeCommand
+ ""
+ formattedMessage)
.sendToTarget();
wait_response = false;
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
try {
ManageDataThread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Write to the connected OutStream.
*
* #param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
wait_response = true;
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
canGo = false;
}
}
public void cancel() {
try {
canGo = false;
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}
With this class i manage the connection like the BluetoothChatSimple example project.
But in my second fragment i need to connect again to the obd2 and take some particular data.
This code is very articulate, there is some better way to do that?
Something that when i change Fragment just stop data exchange from obd and phone but the phone still connected with the obd so in another Fragment i can't send and receive different data by from different Fragments...
PS: I use the manageDataThread for data exchange with obd and get formatted results from hex.
In my mobile robot project, which have 2 servo motors to rotate the camera in two planes I want to control them in my android app by rotation the smartphone (through readings yaw/pitch/roll from the smartphone accelometer).
For that I have to send data about this three angles through Bluetooth to Arduino. So for example sample data packet looks like
"Y:100,P:20,R:45"
where [Y-yaw, P-pitch,R-roll]. However, when I try to send this kind of data packet through Bluetooth from my smartphone to Arduino, in Arduino the packet is received bit by bit, so above shown data packet in Serial Port Monitor looks like:
Y
:
1
0
0
etc. (which makes it much harder to read this data and their correct acquisition, because my smartphone sends as well other data to control the direction of mobile robot [engines]).
So if I using smartphone + Bluetooth + Arduino -> it is possible to send a whole packet of data at once, no bit by bit ???
This is the code from Android Studio (about Bluetooth Activity):
package com.samplecompass;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
public class cBluetooth{
public final static String TAG = "BL_4WD";
private static BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final Handler mHandler;
public final static int BL_NOT_AVAILABLE = 1; // ������ ��� Handler
public final static int BL_INCORRECT_ADDRESS = 2;
public final static int BL_REQUEST_ENABLE = 3;
public final static int BL_SOCKET_FAILED = 4;
public final static int RECIEVE_MESSAGE = 5;
cBluetooth(Context context, Handler handler){
btAdapter = BluetoothAdapter.getDefaultAdapter();
mHandler = handler;
if (btAdapter == null) {
mHandler.sendEmptyMessage(BL_NOT_AVAILABLE);
return;
}
}
public void checkBTState() {
if(btAdapter == null) {
mHandler.sendEmptyMessage(BL_NOT_AVAILABLE);
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "Bluetooth ON");
} else {
mHandler.sendEmptyMessage(BL_REQUEST_ENABLE);
}
}
}
public void BT_Connect(String address) {
Log.d(TAG, "...On Resume...");
if(!BluetoothAdapter.checkBluetoothAddress(address)){
mHandler.sendEmptyMessage(BL_INCORRECT_ADDRESS);
return;
}
else{
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.d(TAG, "In onResume() and socket create failed: " + e.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
btAdapter.cancelDiscovery();
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "In onResume() and unable to close socket during connection failure" + e2.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "In onResume() and output stream creation failed:" + e.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
mConnectedThread = new ConnectedThread();
mConnectedThread.start();
}
}
public void BT_onPause() {
Log.d(TAG, "...On Pause...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
Log.d(TAG, "In onPause() and failed to flush output stream: " + e.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
}
if (btSocket != null) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "In onPause() and failed to close socket." + e2.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
}
}
public void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.i(TAG, "Send data: " + message);
if (outStream != null) {
try {
outStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "In onResume() and an exception occurred during write: " + e.getMessage());
mHandler.sendEmptyMessage(BL_SOCKET_FAILED);
return;
}
} else Log.d(TAG, "Error Send data: outStream is Null");
}
/**
public void write(byte[] bytes) {
try {
outStream.write(bytes);
} catch (IOException e) { System.out.println(e); }
}
**/
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
public ConnectedThread() {
InputStream tmpIn = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = btSocket.getInputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
}
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);
mHandler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
}
}
I'm doing an Bluetooth application which I connect any device and do some work. I have lots of activities. I do all connection stuff in the BlutoothConnectionService.java class. In my BondedDevicesActivity I click a device that I would like to connect. Then service works and another activity is opened. Then I click some buttons which opens another activities. In all activity I'm sending some information via bluetooth. Thus whenever I open another activity I use BlutoothConnectionService.java class. Problem is in this class, it always trying to connect to device. I would like that once it is connected, it never tries it again until connection is dead. But I couldn't figure out how to make that. I know there is a method called isConnected() but I don't know where to put it in the service class. Here is my code of service:
public class BluetoothConnectionService {
private static final String TAG = "BluetoothConnectionSrvc";
private static final UUID connectionUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final BluetoothAdapter bluetoothAdapter;
Context ctx;
private ConnectThread connectThread;
private BluetoothDevice bluetoothDevice;
private UUID deviceUUID;
ProgressDialog progressDialog;
private ConnectedThread connectedThread;
String incomingMessage;
public BluetoothConnectionService(Context context, BluetoothDevice device, UUID uuid) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ctx = context;
startClient(device, uuid);
}
public void startClient(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "startClient: Started.");
connectThread = new ConnectThread(device, uuid);
connectThread.start();
}
private class ConnectThread extends Thread {
private BluetoothSocket bluetoothSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
bluetoothDevice = device;
deviceUUID = uuid;
}
public void run() {
Log.i(TAG, "ConnectThread: Run.");
BluetoothSocket tmp = null;
try {
Log.d(TAG, "ConnectThread: Trying to create RFcommSocket using UUID: " + connectionUUID);
tmp = bluetoothDevice.createRfcommSocketToServiceRecord(deviceUUID);
progressDialog = ProgressDialog.show(ctx, "Cihaza Bağlanılıyor", "Lütfen Bekleyiniz...", true);
} catch (Exception e) {
progressDialog.dismiss();
e.printStackTrace();
Log.e(TAG, "ConnectThread: Couldn't create RFcommSocket" + e.getMessage());
showMessage("Cihaza bağlanılamadı, lütfen bağlantınızı kontrol ederek tekrar deneyiniz.");
AnaEkranActivity.instance.finish();
}
if (tmp != null) {
bluetoothSocket = tmp;
bluetoothAdapter.cancelDiscovery();
try {
bluetoothSocket.connect();
Log.d(TAG, "run: ConnectionThread connected.");
connected(bluetoothSocket);
} catch (Exception e) {
progressDialog.dismiss();
e.printStackTrace();
showMessage("Cihaza bağlanılamadı, lütfen bağlantınızı kontrol ederek tekrar deneyiniz.");
AnaEkranActivity.instance.finish();
try {
bluetoothSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (Exception e1) {
e1.printStackTrace();
Log.e(TAG, "ConnectThread: run: Unable to close connection in socket" + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + connectionUUID);
}
}
}
}
public void connected(BluetoothSocket socket) {
Log.d(TAG, "Connected: Starting.");
connectedThread = new ConnectedThread(socket);
connectedThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
try {
tmpIn = bluetoothSocket.getInputStream();
tmpOut = bluetoothSocket.getOutputStream();
} catch (Exception e) {
e.printStackTrace();
}
inputStream = tmpIn;
outputStream = tmpOut;
}
public void run() {
byte[] readBuffer = new byte[1024];
int readBytes;
while (true) {
try {
readBytes = inputStream.read(readBuffer);
incomingMessage = new String(readBuffer, 0, readBytes);
Log.d(TAG, "InputStream: " + incomingMessage);
showMessage(incomingMessage);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "read: Error reading from inputStream." + e.getMessage());
showMessage("Connection is dead.");
AnaEkranActivity.instance.finish();
break;
}
}
}
public void write(byte[] writeBytes) {
String text = new String(writeBytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputStream: " + text);
try {
outputStream.write(writeBytes);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "write: Error writing to outputStream." + e.getMessage());
showMessage("Error while writing.");
}
}
}
public void write (byte[] out) {
Log.d(TAG, "write: Write Called.");
connectedThread.write(out);
}
public String read () {
Log.d(TAG, "read: Read Called.");
connectedThread.run();
return incomingMessage;
}
public void showMessage(final String toastMessage) {
AnaEkranActivity.instance.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ctx, toastMessage, Toast.LENGTH_SHORT).show();
}
});
}
}
Any idea ?
In android documentation you will get this answer. There we are using same thing in Bluetooth chatting app. Here is the link Bluetooth chat app
Which gives you information about connection. And this explanation
will help you to solve this problem. Go through once clearly you will get the solution.
I'm trying to write a code that only connect to my (for now) only paired device on my Device running Android 5.0 KitKat. No matter how many thing I have tried, I still get this error. This is the last code I have tried, which seems to be doing everything I've seen people report as successful.
Can anybody point me to what I'm doing wrong?
java.io.IOException: bt socket closed, read return: -1
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:517)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
at java.io.InputStream.read(InputStream.java:162)
at biometricreader.BluetoothReaderService$ConnectedThread.run(BluetoothReaderService.java:415)
My java code is
/**
* This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread that listens for
* incoming connections, a thread for connecting with a device, and a
* thread for performing data transmissions when connected.
*/
public class BluetoothReaderService {
// Debugging
private static final String TAG = "BluetoothChatService";
private static final boolean D = true;
// Name for the SDP record when creating server socket
private static final String NAME = "BluetoothChat";
// Unique UUID for this application
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
private InputStream mInStream;
private OutputStream mOutStream;
// APPConstants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
/**
* Constructor. Prepares a new BluetoothChat session.
* #param context The UI Activity Context
* #param handler A Handler to send messages back to the UI Activity
*/
public BluetoothReaderService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
}
/**
* Set the current state of the chat connection
* #param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(Constant.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
/**
* Return the current connection state. */
public synchronized int getState() {
return mState;
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
if (D) Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Start the thread to listen on a BluetoothServerSocket
if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
setState(STATE_LISTEN);
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* #param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
if (D) Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
setState(STATE_CONNECTING);
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* #param socket The BluetoothSocket on which the connection was made
* #param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
if (D) Log.d(TAG, "connected");
// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Cancel the accept thread because we only want to connect to one device
if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(Constant.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Constant.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (D) Log.d(TAG, "stop");
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
* #param out The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) {
Log.d(""+getClass(),"bluetoth reader service mState ***** " + mState);
return ;
}
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/**
* CGPL-17 [satuti] to detect state of device 5/25/2016
*/
public int writeReturn(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) {
Log.d(""+getClass(),"bluetoth reader service mState ***** " + mState);
return mState;
}
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
return mState;
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constant.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constant.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constant.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constant.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
Log.e(TAG, "listen() failed", e);
}
mmServerSocket = tmp;
}
public void run() {
if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
setName("AcceptThread");
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "accept() failed", e);
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothReaderService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
if (D) Log.i(TAG, "END mAcceptThread");
}
public void cancel() {
if (D) Log.d(TAG, "cancel " + this);
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of server failed", e);
}
}
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
if(mmSocket == null){
Log.e(TAG, "mmSocket == null");
}
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
// Start the service over to restart listening mode
BluetoothReaderService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothReaderService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
mInStream = tmpIn;
mOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Constant.MESSAGE_READ, bytes, -1, buffer) .sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
* #param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(Constant.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
public boolean writestream(byte[] buffer)
{
boolean ret=false;
if(mState == STATE_CONNECTED)
{
try {
mOutStream.write(buffer);
ret=true;
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
return ret;
}
public int readstream(byte[] buffer)
{
int bytes=0;
if(mState == STATE_CONNECTED)
{
try {
bytes=mInStream.read(buffer);
} catch (IOException e) {
Log.e(TAG, "Exception during read", e);
}
}
return bytes;
}
}
**
**i am getting this error on my
class ConnectedThread
// Read from the InputStream
bytes = mmInStream.read(buffer);**
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.e(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
mInStream = tmpIn;
mOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Constant.MESSAGE_READ, bytes, -1, buffer) .sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
* #param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(Constant.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
**