0
votes

I'm developing an Android app that is a kind of a remote control (that works via bluetooth) for one Arduino device. I've already could pair my phone with remote Bluetooth. Also it seems that I could establish connection which I've checked with an ACTION_ACL_CONNECTED state like this:

 private final BroadcastReceiver connectedReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            showToast("Conneeeeeeeeeeeeected");
        }
    }
};

The problem is when I press a button on my app to send some data to the remote Bluetooth, nothing happens (a LED must change its state from OFF to ON). Could you please check what's wrong, maybe it's something with my ConnectThread? Here is my code:

public class MainActivity extends AppCompatActivity {

private final static UUID MY_UUID = UUID.fromString("ecff8f1a-ac66-11e6-80f5-76304dec7eb7");

BluetoothSocket mmSocket;

    Button whiteBtn; // after clicking this button, data from my phone are send to remote bluetooth
whiteBtn = (Button) findViewById(R.id.white_btn);
whiteBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        whiteBtnOn();
    }
});


@Override
protected void onCreate(Bundle savedInstanceState) {

    // Get Bluetooth Adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        showToast("Bluetooth is not supported on this device");
    }


    // Enable Bluetooth
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrListPaired);
    pairedListView.setAdapter(mPairedDevicesArrayAdapter);


    // Find out which devices have been already paired
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if (pairedDevices.size() > 0) {
        showToast("Paired devices have been found");
        // Loop through the paired devices
        for (BluetoothDevice device : pairedDevices) {
            arrListPaired.add(device.getName() + '\n' + device.getAddress());
            mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrListPaired); 
        }
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
    }

    // Click event for items from paired devices list (Possible actions: “Connect”, which establishes connection between my phone and remote Bluetooth, “Unpair”, “Cancel”)

    pairedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {

            final String info = ((TextView) view).getText().toString();
            int address = info.indexOf(":");
            final String adr = info.substring(address - 2, info.length());
            final int positionToRemove = position;

            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("What should we do?");
            //builder.setMessage("Unpair this device?");

            builder.setPositiveButton("Unpair", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr);

                    // UNPAIR DEVICES
                    unpair(device);
                    arrListPaired.remove(positionToRemove);
                    mPairedDevicesArrayAdapter.notifyDataSetChanged();
                    // END UNPAIR DEVICES
                }
            });

            builder.setNeutralButton("Cancel", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            });

// Establish Connection between devices
            builder.setNegativeButton("Connect", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    showToast("Establish connection");
                    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr);
                    ConnectThread ct = new ConnectThread(device);
                    ct.start();
                    IntentFilter filter = new IntentFilter();
                    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
                    registerReceiver(connectedReceiver, filter);
                }

            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
    });


        @Override
protected void onPause() {
    if (mBluetoothAdapter != null) {
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
    }
    super.onPause();
}

@Override
protected void onDestroy() {
    unregisterReceiver(mReceiver);
    super.onDestroy();
}


private void showToast(String message) {
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}


private void pairDevice(BluetoothDevice device) {
    try {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(receiver, filter);

        Method method = device.getClass().getMethod("createBond", (Class[]) null);
        method.invoke(device, (Object[]) null);

    } catch (Exception e) {
        e.printStackTrace();

    }
}

private void unpair(BluetoothDevice device) {
    showToast("Unpaired button is clicked");
    try {
        if(mmSocket!=null) {mmSocket.close();}
        Method m = device.getClass().getMethod("removeBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}



// Connecting threat
private class ConnectThread extends Thread {
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;
        mmDevice = device;

        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {}
        mmSocket  = tmp;
    }

    public void run () {
        mBluetoothAdapter.cancelDiscovery();

        try {
            mmSocket.connect();
        } catch (IOException connectException) {

        try {
                mmSocket.close();
            } catch (IOException closeException) {}
            return;
        }
        //manageConnectedSocket(mmSocket);
    }
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {}
    }
}


// Managing a connection

    // Broadcast receiver for connected device
private final BroadcastReceiver connectedReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            showToast("Conneeeeeeeeeeeeected");
        }
    }
};


// Send data after clicking on a button
    private void whiteBtnOn() {
        if (mmSocket != null) {
            showToast("White btn is clicked");
           try {
                mmSocket.getOutputStream().write("TO".toString().getBytes());
            }
            catch (IOException e) {}
        }
    }
    }

}

Thanks in advance for your suggestions!

1
From the Arduino end I have the simplest sketch (turn on a LED if there some incoming info from Bluetooth): /* LEDs */ int led = 7; void setup() { pinMode(led, OUTPUT); Serial.begin(9600); } void loop() { if(Serial.available()) { digitalWrite (led, HIGH); } } Iryna D

1 Answers

0
votes

Try use UUID for Bluetooth SPP:

private final static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

instead of:

private final static UUID MY_UUID = UUID.fromString("ecff8f1a-ac66-11e6-80f5-76304dec7eb7");