0
public String colorHex(int color) {

    int a = Color.alpha(color);
    int r = Color.red(color);
    int g = Color.green(color);
    int b = Color.blue(color);
    return String.format(Locale.getDefault(), "0x%02X%02X%02X%02X", a, r, g, b);
}

I have the code above and i cannot for the life of me figure out how (on the click of a button) to send this hexcode through bluetooth to an arduino. any help would be great.

edit: i have the bluetooth code set up and working ie. i can connect to the arudino.

below is the bluetooth code i am using.

i am using a colorpicker in a seperate class and calling to the bluetooth activity. just having trouble resolving how to send a hexcode as a string through the bluetooth connection

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mInstanceActivity = this;


    mBluetoothStatus = findViewById(R.id.bluetoothStatus);
    mReadBuffer = findViewById(R.id.readBuffer);
    mScanBtn = findViewById(R.id.scan);
    mOffBtn = findViewById(R.id.off);
    mDiscoverBtn = findViewById(R.id.discover);
    mListPairedDevicesBtn = findViewById(R.id.PairedBtn);

    mBTArrayAdapter = new ArrayAdapter<String>(this, 
android.R.layout.simple_list_item_1);
    mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on 
the bluetooth radio

    mDevicesListView = findViewById(R.id.devicesListView);
    mDevicesListView.setAdapter(mBTArrayAdapter); // assign model to view
    mDevicesListView.setOnItemClickListener(mDeviceClickListener);

    Button btn = findViewById(R.id.NextPage);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, Palette.class));

        }});


    mHandler = new Handler(){
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        public void handleMessage(android.os.Message msg){
            if(msg.what == MESSAGE_READ){
                String readMessage = null;
                readMessage = new String((byte[]) msg.obj, 
StandardCharsets.UTF_8);
                mReadBuffer.setText(readMessage);
            }

            if(msg.what == CONNECTING_STATUS){
                if(msg.arg1 == 1)
                    mBluetoothStatus.setText("Connected to Device: " + 
msg.obj);
                else
                    mBluetoothStatus.setText("Connection Failed");
            }
        }
    };










    if (mBTArrayAdapter == null) {
        // Device does not support Bluetooth
        mBluetoothStatus.setText("Status: Bluetooth not found");
        Toast.makeText(getApplicationContext(),"Bluetooth device not 
found!",Toast.LENGTH_SHORT).show();
    }



        mScanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bluetoothOn(v);
            }
        });

        mOffBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                bluetoothOff(v);
            }
        });

        mListPairedDevicesBtn.setOnClickListener(new View.OnClickListener() 
{
            @Override
            public void onClick(View v){
                listPairedDevices(v);
            }
        });

        mDiscoverBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                discover(v);
            }
        });
    }


private void bluetoothOn(View view){
    if (!mBTAdapter.isEnabled()) {
        Intent enableBtIntent = new 
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        mBluetoothStatus.setText("Bluetooth enabled");
        Toast.makeText(getApplicationContext(),"Bluetooth turned 
on",Toast.LENGTH_SHORT).show();

    }
    else{
        Toast.makeText(getApplicationContext(),"Bluetooth is already on", 
Toast.LENGTH_SHORT).show();
    }
}

// Enter here after user selects "yes" or "no" to enabling radio
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent 
Data){
    // Check which request we're responding to
    if (requestCode == REQUEST_ENABLE_BT) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // The user picked a contact.
            // The Intent's data Uri identifies which contact was selected.
            mBluetoothStatus.setText("Enabled");
        }
        else
            mBluetoothStatus.setText("Disabled");
    }
}

private void bluetoothOff(View view){
    mBTAdapter.disable(); // turn off
    mBluetoothStatus.setText("Bluetooth disabled");
    Toast.makeText(getApplicationContext(),"Bluetooth turned Off", 
Toast.LENGTH_SHORT).show();
}

private void discover(View view){
    // Check if the device is already discovering
    if(mBTAdapter.isDiscovering()){
        mBTAdapter.cancelDiscovery();
        Toast.makeText(getApplicationContext(),"Discovery 
stopped",Toast.LENGTH_SHORT).show();
    }
    else{
        if(mBTAdapter.isEnabled()) {
            mBTArrayAdapter.clear(); // clear items
            mBTAdapter.startDiscovery();
            Toast.makeText(getApplicationContext(), "Discovery started", 
Toast.LENGTH_SHORT).show();
            registerReceiver(blReceiver, new 
IntentFilter(BluetoothDevice.ACTION_FOUND));
        }
        else{
            Toast.makeText(getApplicationContext(), "Bluetooth not on", 
Toast.LENGTH_SHORT).show();
        }
    }
}

final BroadcastReceiver blReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(BluetoothDevice.ACTION_FOUND.equals(action)){
            BluetoothDevice device = 
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // add the name to the list
            mBTArrayAdapter.add(device.getName() + "\n" + 
device.getAddress());
            mBTArrayAdapter.notifyDataSetChanged();
        }
    }
};

private void listPairedDevices(View view){
    mPairedDevices = mBTAdapter.getBondedDevices();
    if(mBTAdapter.isEnabled()) {
        // put it's one to the adapter
        for (BluetoothDevice device : mPairedDevices)
            mBTArrayAdapter.add(device.getName() + "\n" + 
device.getAddress());

         Toast.makeText(getApplicationContext(), "Show Paired Devices", 
Toast.LENGTH_SHORT).show();
    }
    else
        Toast.makeText(getApplicationContext(), "Bluetooth not on", 
Toast.LENGTH_SHORT).show();
}

private AdapterView.OnItemClickListener mDeviceClickListener = new 
AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) 
{

        if(!mBTAdapter.isEnabled()) {
            Toast.makeText(getBaseContext(), "Bluetooth not on", 
Toast.LENGTH_SHORT).show();
            return;
        }

        mBluetoothStatus.setText("Connecting...");
        // Get the device MAC address, which is the last 17 chars in the 
View
        String info = ((TextView) v).getText().toString();
        final String address = info.substring(info.length() - 17);
        final String name = info.substring(0,info.length() - 17);


        // Spawn a new thread to avoid blocking the GUI one
        new Thread()
        {
            public void run() {
                boolean fail = false;

                BluetoothDevice device = 
mBTAdapter.getRemoteDevice(address);

                try {
                    mBTSocket = createBluetoothSocket(device);
                } catch (IOException e) {
                    fail = true;
                    Toast.makeText(getBaseContext(), "Socket creation 
failed", Toast.LENGTH_SHORT).show();
                }
                // Establish the Bluetooth socket connection.
                try {
                    mBTSocket.connect();
                } catch (IOException e) {
                    try {
                        fail = true;
                        mBTSocket.close();
                        mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
                                .sendToTarget();
                    } catch (IOException e2) {
                        //insert code to deal with this
                        Toast.makeText(getBaseContext(), "Socket creation 
failed", Toast.LENGTH_SHORT).show();
                    }
                }
                if(fail == false) {
                    mConnectedThread = new ConnectedThread(mBTSocket);
                    mConnectedThread.start();

                    mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
                            .sendToTarget();
                }
            }
        }.start();
    }
};

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) 
throws IOException {
    return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
    //creates secure outgoing connection with BT device using UUID
}

public 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.available();
                if(bytes != 0) {
                     SystemClock.sleep(100); //pause and wait for rest of 
data. Adjust this depending on your sending speed.
                    bytes = mmInStream.available(); // how many bytes are 
ready to be read?
                    bytes = mmInStream.read(buffer, 0, bytes); // record 
how many bytes we actually read
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget(); // Send the obtained bytes to 
the UI activity
                }
            } catch (IOException e) {
                e.printStackTrace();

                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device 
*/
    public void write(String input) {
        byte[] bytes = input.getBytes();           //converts entered 
String into bytes
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
protected void onDestroy(){
    super.onDestroy();
    mInstanceActivity = null;

}

}

and i am trying to send the hexcode with the following code:

SendColor.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            if(mConnectedThread != null) //First check to make sure thread 
created
                mConnectedThread.write(colorHex());
        }
    });
  • The code for your colorHex is pretty pointless for this question. It would likely be more helpful if you provided your bluetooth connection code instead, and showed how you are trying to send data. – Quinn Jan 29 '20 at 21:36
  • Perhaps [this](https://stackoverflow.com/questions/22899475/android-sample-bluetooth-code-to-send-a-simple-string-via-bluetooth) may help you? – Quinn Jan 29 '20 at 21:39
  • i tried posting my bluetooth code but it wont let me – BlueSpider5 Jan 29 '20 at 21:42
  • got the code uploaded – BlueSpider5 Jan 29 '20 at 21:48
  • I suspect that your device doesn't want a human readable hex string, but instead a series of bytes. Sending the byte `0x05` vs the byte `5` is the same difference as picking "5 apples" vs picking "five apples" (i.e. different ways of writing the exact same thing) – that other guy Jan 29 '20 at 21:53

0 Answers0