0

I am done with connecting the Bluetooth to a paired device. After establishing the connection I want to move to the next activity, where the data to be sent are given by the user. so the main thing is, how can I send a string to an already connected Bluetooth device(from previous activity). Need help. I searched a lot. Couldn't find it. Thanks in advance

BluetoothConnectingActivity

private Runnable serverListener = new Runnable() { public void run() { try //opening of BT connection { //problematic with older phones... HELP: Change server/client orientation... //but solves: BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback

            Log.i("TrackingFlow", "Server socket: new way used...");
            socket = (BluetoothSocket) remoteDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(remoteDevice, 1);
            socket.connect();
            CONNECTION_ENSTABLISHED = true; //protect from failing

        } catch (Exception e) //obsolete way how to open BT
        {
            try {
                Log.e("TrackingFlow", "Server socket: old way used...");
                BluetoothServerSocket tmpsocket = adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
                socket = tmpsocket.accept();
                CONNECTION_ENSTABLISHED = true; //protect from failing
                Log.i("TrackingFlow", "Listening...");
            } catch (Exception ie) {
                Log.e(TAG, "Socket's accept method failed", ie);
                ie.printStackTrace();
            }
        }

        Log.i(TAG, "Server is ready for listening...");

        runOnUiThread(new Runnable() {
            @Override
            public void run() { //Show message on UIThread
                listItems.clear(); //remove chat history
                listItems.add(0, String.format("  Server opened! Waiting for clients..."));
                listAdapter.notifyDataSetChanged();

            }
        });


        try //reading part
        {
            is = socket.getInputStream();
            os = socket.getOutputStream();
            new Thread(writter).start();


            int bufferSize = 1024;
            int bytesRead = -1;
            byte[] buffer = new byte[bufferSize];

            while (CONTINUE_READ_WRITE) //Keep reading the messages while connection is open...
            {
                final StringBuilder sb = new StringBuilder();
                bytesRead = is.read(buffer);
                if (bytesRead != -1) {
                    String result = "";
                    while ((bytesRead == bufferSize) && (buffer[bufferSize - 1] != 0)) {
                        result = result + new String(buffer, 0, bytesRead - 1);
                        bytesRead = is.read(buffer);
                    }
                    result = result + new String(buffer, 0, bytesRead - 1);
                    sb.append(result);
                }
                Log.e("TrackingFlow", "Read: " + sb.toString());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() { //Show message on UIThread
                        Toast.makeText(ConnectToBluetoothActivity.this, sb.toString(), Toast.LENGTH_SHORT).show();
                        listItems.add(0, String.format("< %s", sb.toString())); //showing in history
                        listAdapter.notifyDataSetChanged();
                    }
                });
            }
        } catch (IOException e) {
            Log.e(TAG, "Server not connected...");
            e.printStackTrace();
        }
    }
};

StringSendingActivity

public void sendString(String convertedString) { //send converted string

    byte[] b = convertedString.getBytes();

    try {

        Toast.makeText(this, "Sending" + convertedString, Toast.LENGTH_SHORT).show();
        os.write(b);
        // list.add(0, "> " + et.getText().toString()); //chat history

        list.add(0, et.getText().toString()); //chat history

        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.message_textview, R.id.textview, list);
        listview.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        et.setText(""); //remove text after sending


    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
    }
}
user7418129
  • 1,074
  • 14
  • 18
  • I'm in very urgent. please help. I will be thankful. – user7418129 Dec 13 '18 at 07:03
  • https://stackoverflow.com/questions/22899475/android-sample-bluetooth-code-to-send-a-simple-string-via-bluetooth try this – rak Dec 13 '18 at 07:07
  • Thank you @rak your fast reply. In the link that given, It is again trying to connect to the device. But actually, I already established the connection in previous activity – user7418129 Dec 13 '18 at 09:10
  • https://stackoverflow.com/questions/25577645/how-to-send-data-a-string-to-a-paired-device-in-android check – rak Dec 13 '18 at 09:36
  • Thank you, But here it is again connecting in that activity @rak I just want to send a string in a single activity. Please help – user7418129 Dec 13 '18 at 10:53
  • In your code, is `os.write(b);` the command you used to send string over BT? Are you using BTLE or BT Classic? – HarryQ Dec 13 '18 at 16:49
  • I don't know whether it is BTLE or classic. thank you @HarryQ – user7418129 Dec 14 '18 at 15:29
  • You can preserve the connection across activities in Android BLE. Just provide the target device address, and target characteristic UUID, you can keep writing to the remote device in different activity. – HarryQ Dec 14 '18 at 19:55
  • Thank you for your reply. I'm using BLE, Actually, I'm new in Bluetooth. So I don't understand how to provide the connected device address. any help please ? Thank you in advance. – user7418129 Dec 17 '18 at 07:24
  • Found a solution that, Instead of connecting in the previous activity, I just passed the selected bluetooth address to the next activity. and by that connection established uing, //to get list of paired devices adapter = getDefaultAdapter(); pairedDevices = adapter.getBondedDevices(); – user7418129 Dec 20 '18 at 05:26
  • Are all those activities come from the same app? I would suggest managing Bluetooth connection from a Service. For messaging, you can use broadcasts to create a request-response behavior between an activity and the Service (like requesting current paired device's name and MAC address). Or, maybe (without using Broadcast), you can just store the info in a SharedPreference since most of the time you are going to use the same paired device until you change it. – ecle Dec 20 '18 at 07:36

0 Answers0