Bluetooth IsConnected()

时间:2017-08-05 11:48:42

标签: java android bluetooth

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 ?

1 个答案:

答案 0 :(得分:0)

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.