My demo is just determined to build a connection between two phones.But when my client tries to call bluetoothSocket.connect() it throws an IOException with the message no route to host.I have tried many approaches but it doesn't work.
Here is my code about AcceptThread and ConnectThread (deleted some unrelated code to make it more concise)
class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
BluetoothServerSocket tmp;
public AcceptThread() {
Method listenMethod = null;
try {
listenMethod = bluetoothAdapter.getClass().getMethod("listenUsingRfcommOn",new Class[]{int.class});
}
try {
tmp = ( BluetoothServerSocket) listenMethod.invoke(bluetoothAdapter, new Object[]{30});
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
while (isAcceptRun) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.i(TAG, "run: AB "+e);
break;
}
if (socket != null) {
try {
mmServerSocket.close();
}
break;
}
}
}
}
class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
Method m = null;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
}
try {
tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(30));
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
bluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) {
}
return;
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
In the BluetoothChat example from Google, the BluetoothSocket is constructed by:
private static final UUID MY_UUID_SECURE =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
}
Related
I try to connect to the device used by Bluetooth. When I try to connect I get :
java.io.IOException: read failed, socket might be closed or timeout, read ret: -1
I do this:
BluetoothSocket mmSocket;
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) {
}
mmSocket = tmp;
}
And when I do this :
mmSocket.connect();
I get a exceptions
This is my connect thread :
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) {
}
mmSocket = tmp;
}
public void run() {
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) {
e.printStackTrace();
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
e2.printStackTrace();
}
// Start the service over to restart listening mode
BluetoothChatService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Whenever i try to write something through the socket created I get a Broken Pipe exception on the Connected thread, I followed the examples on the Android development pages (Create three diferent threads, to connect, to accept, and to receive data) but for some reason everytime i try to send something the thread is close
the class I created is the following:
public class BluetoothService {
private static final UUID MY_UUID =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME = "Guess the Movie";
private BluetoothAdapter mBluetoothAdapter;
private Context context;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
public BluetoothService(Context context) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
this.context = context;
}
private void manageConnectedSocket(BluetoothSocket socket, BluetoothDevice device) {
// TODO: 25/06/2017
Log.d(TAG, "socket received" + socket);
connected(socket, device);
}
public synchronized void connect(BluetoothDevice device) {
Log.d(TAG, "connect to: " + device);
// 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 connect with the given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
// Update UI title
//updateUserInterfaceTitle();
}
public synchronized void start() {
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();
}
// Update UI title
//updateUserInterfaceTitle();
}
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
device) {
Log.d(TAG, "connected() called");
// 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();
Log.d(TAG, "connected() finished");
// 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();
*/
}
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
r = mConnectedThread;
}
// Perform the write unsynchronized
Log.d(TAG, "write() called");
r.write(out);
Log.d(TAG, "write() finished");
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(socket, socket.getRemoteDevice());
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
/**
* Will cancel the listening socket, and cause the thread to finish
*/
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) {
}
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket, mmDevice);
}
/**
* Will cancel an in-progress connection, and close the socket
*/
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
//mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
// .sendToTarget();
processarMensagem(bytes);
Log.d(TAG, "received: " + bytes);
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
Log.d(TAG, "sent: " + bytes);
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
}
Disconnect the Bluetooth socket and Outputstreem
public void Disconnect Socket(){
try {
if (DpBtOutputStream!=null)
DpBtOutputStream.close();
}
if (DpBluetoothSocket!=null)
DpBluetoothSocket.close();
catch (Exception e){
}
}
I want to connect android mobile to one electronic device,but I want to connect it insecurely.but its giving me the error of "java.io.IOException: read failed, socket might closed or timeout, read ret: -1"
here is my code
package net.londatiga.android.bluetooth;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final UUID WELL_KNOWN_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,because
// mmSocket is final
BluetoothSocket tmp = null;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// tmp = device.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
tmp = device
.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
Object[] params = new Object[] {Integer.valueOf(1)};
// This is the trick
Method m = device.getClass().getMethod("createInsecureRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, params);
} catch (Exception e) {
e.printStackTrace();
}
mmSocket = tmp;
}
#SuppressLint("NewApi")
public void run() {
// DebugLog.i(TAG, "Trying to connect...");
// Cancel discovery because it will slow down the connection
MainActivity.mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
boolean val=mmSocket.isConnected();
Log.v("val", ""+val);
// DebugLog.i(TAG, "Connection stablished");
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
// DebugLog.e(TAG, "Fail to connect!", connectException);
try {
mmSocket.close();
} catch (IOException closeException) {
// DebugLog.e(TAG, "Fail to close connection", closeException);
}
return;
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
You have to implement an another thread, like below, which always receives your calls and does operations. Start this thread when you start the application.
class AcceptThread extends
Thread {
private final BluetoothServerSocket serverSocket;
private boolean flag = true;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = bluetoothAdapter
.listenUsingInsecureRfcommWithServiceRecord(
NAME_UUID, uuid);
} catch (IOException e) {
}
serverSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
socket = serverSocket.accept();
if (socket.isConnected()) {
Log.d(TAG, "run: connection successfull");
Log.d(TAG, "run: " + socket.getRemoteDevice().getName() + " " +
socket.getRemoteDevice().getAddress());
}
} catch (IOException e) {
try {
socket.close();
} catch (Exception eee) {
Log.d(TAG, "run: " + eee.getMessage());
}
break;
}
}
}
public void cancel() {
try {
serverSocket.close();
} catch (IOException e) {
}
}
}
public class ConnectThread extends Thread
{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final OutputStream mmOutStream;
private UUID uuid = UUID.randomUUID();
private byte[] temp;
public ConnectThread(BluetoothDevice device,byte[] temp)
{
BluetoothSocket socket = null;
OutputStream tmpOut = null;
mmDevice = device;
this.temp = temp;
try
{
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
tmpOut = socket.getOutputStream();
}
catch (Exception e) { }
mmSocket = socket;
mmOutStream = tmpOut;
}
public void run()
{ enter code here
try
{
mmSocket.connect();
write(temp);
}
catch (IOException connectException)
{
try
{
mmSocket.close();
}
catch (IOException closeException)
{ }
return;
}
}
public void write(byte[] bytes)
{
try
{
mmOutStream.write(bytes);
mmOutStream.flush();
mmOutStream.close();
}
catch (IOException e) { }
}
public void cancel()
{
try
{
mmSocket.close();
}
catch (IOException e) { }
}
}
I am trying to transfer a txt file to another device. I am passing the bluetooth device and message(in bytes) to this class and starting the thread form main activity. After scanning, the devices displaying and pairing is also working. I am not getting any exception in the code. But I am not receiving a file.
Why I am not receiving a file on other mobile?
Can somebody help me please.
Thanks, Faraz
Using Android's Bluetooth Chat sample app as my guide http://developer.android.com/resources/samples/BluetoothChat/index.html, I've tried to create my own bluetooth function for an app I am working on.
Last night I tested it with two Android phones and had some issues, but there were no force closes. It simply didn't connect my devices when I asked it to. I went in and added a few Log lines to make sure the program was following the proper course. When I reinstalled and launched the app on my phone today, I got a force close error when attempting to turn on Bluetooth, a problem I did not have at all last night. The only code I changed was the addition of 2-3 log commands. I checked logcat and got the following:
As you can see, the problem is caused by an NPE # line 185. Here is my code for the BluetoothService class, I will repost the specific area of issue below it.
package com.tagapp.android;
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.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class BluetoothService {
private static final String TAG = "BluetoothService";
private static final boolean D = true;
private static final String NAME = "BluetoothTag";
private static final UUID MY_UUID =
UUID.fromString("93845760-234e-11e0-ac64-0800200c9a66");
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public BluetoothService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
}
private synchronized void setState(int state) {
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;
mHandler.obtainMessage(BluetoothTransfer.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
public synchronized int getState() {
return mState;
}
public synchronized void start() {
if (D) Log.d(TAG, "start");
if(mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if(mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if(mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
setState(STATE_LISTEN);
}
public synchronized void connect(BluetoothDevice device) {
if (D) Log.d(TAG, "connect to: " + device);
if(mState == STATE_CONNECTING) {
if(mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
if(mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
mConnectThread = new ConnectThread(device);
mConnectThread.start();
setState(STATE_CONNECTING);
}
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
if (D) Log.d(TAG, "connected");
if(mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if(mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if(mAcceptThread != null) {
mAcceptThread.cancel();
mAcceptThread = null;
}
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
Message msg = mHandler.obtainMessage(BluetoothTransfer.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(BluetoothTransfer.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
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);
}
public void write(byte[] out) {
ConnectedThread ct;
synchronized(this) {
if(mState != STATE_CONNECTED) return;
ct = mConnectedThread;
}
ct.write(out);
}
private void connectionFailed() {
setState(STATE_LISTEN);
Message msg = mHandler.obtainMessage(BluetoothTransfer.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothTransfer.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
private void connectionLost() {
setState(STATE_LISTEN);
Message msg = mHandler.obtainMessage(BluetoothTransfer.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothTransfer.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
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;
while (mState != STATE_CONNECTED) {
try {
socket = mmServerSocket.accept();
}
catch (IOException e) {
Log.e(TAG, "accept() failed", e);
break;
}
if(socket != null) {
synchronized (BluetoothService.this) {
switch(mState) {
case STATE_LISTEN :
case STATE_CONNECTING :
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE :
case STATE_CONNECTED :
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);
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
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");
mAdapter.cancelDiscovery();
try {
mmSocket.connect();
}
catch (IOException e) {
connectionFailed();
try {
mmSocket.close();
}
catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
BluetoothService.this.start();
return;
}
synchronized (BluetoothService.this) {
mConnectThread = null;
}
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
}
catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
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;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}
catch (IOException e) {
Log.e(TAG, "tempt sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(BluetoothTransfer.CONTACT_RECEIVE, bytes, -1, buffer).sendToTarget();
}
catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
mHandler.obtainMessage(BluetoothTransfer.CONTACT_SEND, -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);
}
}
}
}
The lines which are causing the NPE (the AcceptThread):
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
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;
while (mState != STATE_CONNECTED) {
try {
socket = mmServerSocket.accept();//THIS LINE CAUSES NPE
}
catch (IOException e) {
Log.e(TAG, "accept() failed", e);
break;
}
The object socket should by initialized # null, but it is supposed to try socket = mmServerSocket.accept();
This is directly from Google's sample app provided on the Android dev website. I have two concerns: 1, why isn't this working, and 2, why did it work just fine just hours ago?
Thanks for your help.
Regarding "strange NPE" - it's not strange at all. The reason you get NPE at this line
socket = mmServerSocket.accept(); //THIS LINE CAUSES NPE
is pretty obvious - variable mmServerSocket equals NULL, and this is the only possible reason to get NPE at this line of code. The reason why mmServerSocket equals NULL is simple too - look at a constructor of your class:
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
}
catch (IOException e) {
Log.e(TAG, "listen() failed", e);
}
mmServerSocket = tmp;
}
You are calling method listenUsingRfcommWithServiceRecord which throws IOException, you catching this exception, as we can clearly see in logcat. Next, tmp variable stays initialized as NULL, same as mmServerSocket, which leads as to NPE mentioned above.
The reason why listenUsingRfcommWithServiceRecord is throwing IOException - because bluetooth is turned off, as you mention in your question. Android documentation says nothing about your assumption that this method should automatically turn on bluetooth if it's turned off. I think you should manually check if bluetooth is turned off and turn it on manually, before calling listenUsingRfcommWithServiceRecord.
You can find how to check is bluetooth turned on/off and turn it on here and here