Unable to read data from usb serial device in android - android

I went through lots of demos and SO threads before asking this, but none of them is working for me. I am trying to read data over usb serial port using the below code.
public class MainActivity extends Activity {
public final String ACTION_USB_PERMISSION = "com.myprject.usbex.USB_PERMISSION";
Button startButton, sendButton, clearButton, stopButton;
TextView textView;
EditText editText;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
Toast.makeText(MainActivity.this, "Callback Received"+arg0, Toast.LENGTH_SHORT).show();
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Exception:"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
};
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
setUiEnabled(true);
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
try {
serialPort.read(mCallback);
Toast.makeText(MainActivity.this, "Read"+serialPort.read(mCallback), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Exception in read:"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
tvAppend(textView, "Serial Connection Opened!\n");
Toast.makeText(MainActivity.this, "Serial port connected", Toast.LENGTH_SHORT).show();
} else {
Log.d("SERIAL", "PORT NOT OPEN");
}
} else {
Log.d("SERIAL", "PORT IS NULL");
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart(startButton);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop(stopButton);
}
}
;
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(broadcastReceiver, filter);
}
public void setUiEnabled(boolean bool) {
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public void onClickStart(View view) {
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
if (deviceVID == 1659)//Arduino Vendor ID
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
} else {
connection = null;
device = null;
}
if (!keep)
break;
}
}
}
public void onClickSend(View view) {
String string = editText.getText().toString();
serialPort.write(string.getBytes());
tvAppend(textView, "\nData Sent : " + string + "\n");
}
public void onClickStop(View view) {
setUiEnabled(false);
serialPort.close();
tvAppend(textView,"\nSerial Connection Closed! \n");
}
public void onClickClear(View view) {
textView.setText(" ");
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
}
I want to read data continuously from the usb. With above code I am able to get device vendor-id and serialPort.open() is also working. Problem is that I am not receiving the data.
Library used with this code is from here https://github.com/felHR85/SerialPortExample.
Point me where I am going wrong. open for any alternative solution to read data over usb in Android.

The code seems to be right and is working properly. Tried it and it runs smoothly without any problems. You might want to rearrange your widgets a little bit, which could be obstructing/interfering with your output (although I don't think this could be the problem). The toast in onReceivedData function was causing the app to crash. Also, check your Arduino device vendor ID. Mine was different (0x2341 for Arduino UNO R3).

Hello I know its too late for a reply but here it goes.
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
Make sure that these are the config set at your USB Device, try changing BaudRate

i guess that library is specially designed for Arduino and some boards. I tried with PSOc Usb serial data transfer from its ROM, The data was not able to be read properly.

Related

Android Studio Bluetooth ListView

I wanted to make bluetooth applications for arduino so that I could connect to the HC-05 module. And I found a tutorial on how to make a bluetooth connection (http://mcuhq.com/27/simple-android-bluetooth-application-with-arduino-example) When I downloaded the code from github, the application starts and everything works and connects. But the problem is that I can't open a new activity because the project is probably for 15 API and the new activity needs at least 16 so I decided to make such an application on my own based on the code from this website. And here I have a problem because when I make my phone search for bluetooth devices, nothing is displayed on my ListView.
This is my code `
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
offon = findViewById(R.id.BtBtn);
TV = findViewById(R.id.BtTv);
TV2 = findViewById(R.id.textView2);
TV3 = findViewById(R.id.bluetooth_status);
Next = findViewById(R.id.button2);
LV = findViewById(R.id.ListView);
disc = findViewById(R.id.button3);
ArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
adapter = BluetoothAdapter.getDefaultAdapter();
LV.setAdapter(ArrayAdapter);
LV.setOnItemClickListener(DeviceList);
handler = new Handler(Looper.getMainLooper()){
#Override
public void handleMessage(Message msg){
if(msg.what == MESSAGE_READ){
String readMessage = null;
readMessage = new String((byte[]) msg.obj, StandardCharsets.UTF_8);
TV2.setText(readMessage);
}
if(msg.what == CONNECTING_STATUS){
char[] sConnected;
if(msg.arg1 == 1)
TV3.setText(getString(R.string.BTConnected) + msg.obj);
else
TV3.setText(getString(R.string.BTconnFail));
}
}
};
if (adapter.isEnabled()){
TV.setText("Bluetooth ON");
}else TV.setText("Bluetooth OFF");
disc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
discovery();
if (!adapter.isEnabled()){
Toast.makeText(getBaseContext(), getString(R.string.BTnotOn), Toast.LENGTH_SHORT).show();
}
}
});
offon.setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#Override
public void onClick(View view) {
if (adapter.isEnabled()) {
adapter.disable();
TV.setText("Bluetooth OFF");
}else {
adapter.enable();
TV.setText("Bluetooth ON");
}
}
});
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
open2activity();
}
});
}
public void open2activity(){
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode, resultCode, Data);
}
#SuppressLint("MissingPermission")
private void discovery(){
if (adapter.isDiscovering()){
adapter.cancelDiscovery();
Toast.makeText(getApplicationContext(), getString(R.string.DisStop), Toast.LENGTH_SHORT).show();
}
else{
if (adapter.isEnabled()){
ArrayAdapter.clear();
adapter.startDiscovery();
Toast.makeText(getApplicationContext(), getString(R.string.DisStart), Toast.LENGTH_SHORT).show();
registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
}
final BroadcastReceiver blReceiver = new BroadcastReceiver() {
#SuppressLint("MissingPermission")
#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);
ArrayAdapter.add(device.getName() + "\n" + device.getAddress());
ArrayAdapter.notifyDataSetChanged();
}
}
};
private AdapterView.OnItemClickListener DeviceList = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TV3.setText(getString(R.string.cConnet));
String info = ((TextView)view).getText().toString();
final String address = info.substring(info.length() - 17);
final String name = info.substring(0,info.length() - 17);
new Thread()
{
#SuppressLint("MissingPermission")
#Override
public void run() {
boolean fail = false;
BluetoothDevice device = adapter.getRemoteDevice(address);
try {
BTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), getString(R.string.ErrSockCrea), Toast.LENGTH_SHORT).show();
}
try {
BTSocket.connect();
} catch (IOException e) {
try {
fail = true;
BTSocket.close();
handler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
Toast.makeText(getBaseContext(), getString(ErrSockCrea), Toast.LENGTH_SHORT).show();
}
}
if(!fail) {
ConnectedThread = new ConnectedThread(BTSocket, handler);
ConnectedThread.start();
handler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();
}
}
}.start();
}
};
#SuppressLint("MissingPermission")
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
return (BluetoothSocket) m.invoke(device, BT_MODULE_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
return device.createRfcommSocketToServiceRecord(BT_MODULE_UUID);
}
}
`
I tried to do as above but nothing is displayed

Android Studio - searching bluetooth devices

I would like to write an app that can search bluetooth devices, add founded devices to ListView, connect with one of this devices and send some text. But now I am not able to search devices. When I was overlooking logs I noticed that sometimes the searching works. But even if it worked nothing was added to the ListView.
It can be important - I have devices with Android 4.2 and 5.1.
Could anybody help me find mistakes in my code?
This is my code:
public class MainActivity extends Activity {
Button btnSearch;
Button btnConnect;
Button btnSend;
ListView lvDeviceList;
TextView tvOutgoingMessage;
TextView tvIncomingMessage;
BluetoothAdapter bluetoothAdapter;
BroadcastReceiver broadcastReceiver;
public ArrayList<String> BTDevices = new ArrayList<>();
public ListAdapter deviceListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "ONCREATE");
btnSearch = (Button) findViewById(R.id.btnSearch);
btnConnect = (Button) findViewById(R.id.btnConnect);
btnSend = (Button) findViewById(R.id.btnSend);
lvDeviceList = (ListView) findViewById(R.id.devicesList);
tvOutgoingMessage = (TextView) findViewById(R.id.outgoingMessage);
tvIncomingMessage = (TextView) findViewById(R.id.incommingMessage);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (checkIfEnable()) {
Log.d(TAG, "ONCREATE - IF");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
discoverDevices();
connect();
}
}
});
}
public boolean checkIfEnable() {
boolean existance = true;
Log.d(TAG, "CHECK IF ENABLE");
if (bluetoothAdapter == null) {
Log.d(TAG, "IN 1ST IF");
Toast.makeText(getApplicationContext(), "Your device doesn't support Bluetooth", Toast.LENGTH_LONG).show();
existance = false;
}
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
Log.d(TAG, "IN 2ND IF");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
return existance;
}
private void discoverDevices() {
Log.d(TAG, "DISCOVER DEVICES");
bluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
// Create a BroadcastReceiver for ACTION_FOUND.
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "ON RECEIVE");
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
BTDevices.add(deviceName);
lvDeviceList.setAdapter(deviceListAdapter);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
}
}
};
}
private void connect() {
Log.d(TAG, "CONNECT");
}
Thanks in advance.
First of all, you shouldn't call lvDeviceList.setAdapter(deviceListAdapter) on each device found. Move this line to onCreate(). The second - you should pass BTDevices to your adapter(this part is important and it's missing in your code) and on each BTDevices.add(deviceName) you should call notifyDataSetChanged() on your adapter.

Bluetooth Connection

I've looked at quite a lot of topics on this in different forums and none seem to help me.
I recently bought an Elegoo car kit, which is compatible with the Arduino IDE, and it comes with different types of code and what not. they even have their own Android app.
My problem is I want to create my own android Bluetooth application that connects/pairs with the module and can control the car remotely. I have my application up and running, it can scan for nearby devices and the HC-08 module appears in the list but I am not able to connect. when I try to connect it says it can't communicate with HC-08. I am pretty sure the problem lies in the android end as the elegoo Bluetooth app connects no problem at all with the Bluetooth module if there is any code on the elegoo board or not. The bluetooth module is a HC-08.
Can someone help me with this ?
Also I am following this youtube tutorial so the credit goes to him for the code.
https://www.youtube.com/watch?v=YJ0JQXcNNTA
Here is the main activity code:
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener{
private static final String TAG = "MainActivity";
BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
/**
* Broadcast Receiver for changes made to bluetooth states such as:
* 1) Discoverability mode on/off or expire.
*/
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
/**
* Broadcast Receiver for listing devices that are not yet paired
* -Executed by btnDiscover() method.
*/
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
/**
* Broadcast Receiver that detects bond state changes (Pairing status changes)
*/
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
#Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
//mBluetoothAdapter.cancelDiscovery();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable(View view) {
Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover(View view) {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
/// Here is also my DeviceListAdapter code:
public class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {
private LayoutInflater mLayoutInflater;
private ArrayList<BluetoothDevice> mDevices;
private int mViewResourceId;
public DeviceListAdapter(Context context, int tvResourceId, ArrayList<BluetoothDevice> devices){
super(context, tvResourceId,devices);
this.mDevices = devices;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = tvResourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflater.inflate(mViewResourceId, null);
BluetoothDevice device = mDevices.get(position);
if (device != null) {
TextView deviceName = (TextView) convertView.findViewById(R.id.tvDeviceName);
TextView deviceAdress = (TextView) convertView.findViewById(R.id.tvDeviceAddress);
if (deviceName != null) {
deviceName.setText(device.getName());
}
if (deviceAdress != null) {
deviceAdress.setText(device.getAddress());
}
}
return convertView;
}
}
Some of the tutorials on Bluetooth are pretty old! I just got Arduino-Android Bluetooth communication working last week so this should work for you! First in your manifest file add these permissions:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then use this in your main.
public class MainActivity extends AppCompatActivity {
private final String DEVICE_ADDRESS="benamekhoda"; //I actually used Device Name instead of address
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Serial Port Service UUID
private BluetoothDevice device; //Our Bluetooth Device
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Button startButton, sendButton,clearButton,stopButton;
TextView textView;
EditText editText;
boolean deviceConnected=false;
Thread thread;
byte buffer[];
int bufferPosition;
boolean stopThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.edittext);
textView = (TextView) findViewById(R.id.textview);
startButton = (Button) findViewById(R.id.buttonStart);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
textView.append("\nConnection Opened!\n");
}
else{
Toast.makeText(getApplicationContext(),"BTconnect false",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getApplicationContext(),"BTinit false",Toast.LENGTH_SHORT).show();
}
}
});
sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String string = editText.getText().toString();
string.concat("\n");
try {
outputStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append("\nSent Data:"+string+"\n");
}
});
clearButton = (Button) findViewById(R.id.buttonClear);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickClear(view);
}
});
stopButton = (Button) findViewById(R.id.buttonStop);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickSend(view);
}
});
setUiEnabled(false);
}
public void setUiEnabled(boolean bool)
{
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public boolean BTinit()
{
boolean found=false;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices(); //Something like ArrayList but no duplicate is allowed and data is unordered
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
if(iterator.getName().equals(DEVICE_ADDRESS))
{
device=iterator;
Toast.makeText(getApplicationContext(),"found the device",Toast.LENGTH_SHORT).show();
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw1",Toast.LENGTH_SHORT).show();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw2",Toast.LENGTH_SHORT).show();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw3",Toast.LENGTH_SHORT).show();
}
}
return connected;
}
void beginListenForData()
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string=new String(rawBytes,"UTF-8");
handler.post(new Runnable() {
public void run()
{
textView.append(string);
}
});
}
}
catch (IOException ex)
{
stopThread = true;
Toast.makeText(getApplicationContext(),"throw4",Toast.LENGTH_SHORT).show();
}
}
}
});
thread.start();
}
public void onClickSend(View view) {
String string = editText.getText().toString();
string.concat("\n");
try {
outputStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append("\nSent Data:"+string+"\n");
}
public void onClickStop(View view) throws IOException {
stopThread = true;
outputStream.close();
inputStream.close();
socket.close();
setUiEnabled(false);
deviceConnected=false;
textView.append("\nConnection Closed!\n");
}
public void onClickClear(View view) {
textView.setText("");
}
}
I got it from this awesome tutorial by Hariharan Mathavan from All About Circuits.

How to read two BLE characteristics of two services at the same interface page?

I am trying to manage my temperature service and LED service of my BLE device at the same Android interface. However, whenever I try to turn the LED on, the app dies, and I don't know how to fix this (I am not good at either Java or BLE).
I have all of the UUIDs of the characteristics and services I need. I am trying to create two BluetoothGattCharacteristic
private BluetoothGattCharacteristic characteristic;
private BluetoothGattCharacteristic characteristicCTRL2;
It works fine when I call the temperature characteristic and get the temperature measurement. However, the app dies whenever I try to turn the LED on /call the LED characteristic.
10-30 08:48:33.026 1033-1033/com.example.android.bluetoothlegatt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.bluetoothlegatt, PID: 1033
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothGattCharacteristic.setValue(byte[])' on a null object reference
at com.example.android.bluetoothlegatt.AutoConnectActivity.turnLEDon(AutoConnectActivity.java:71)
at com.example.android.bluetoothlegatt.AutoConnectActivity$6.onClick(AutoConnectActivity.java:264)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19754)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5219)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The following code is how I transfer all characteristics & services together.
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
if ( gattCharacteristic.getUuid().equals(UUID.fromString(SampleGattAttributes.CTRL_2))){ //CTRL_2 is the UUID of my LED characteristic
Log.e(TAG, "GattCharacteristics= " + gattCharacteristic.getUuid());
Intent intent = new Intent(DeviceControlActivity.this, AutoConnectActivity.class);
intent.putExtra("character_id", "F000AA01-0451-4000-B000-000000000000"); //UUID of my temperature characteristic
intent.putExtra("service_id", "F000AA00-0451-4000-B000-000000000000");//UUID of my temperature service
intent.putExtra("address", mDeviceAddress);
intent.putExtra("ctrl2_character_id", gattCharacteristic.getUuid().toString()); //UUID of my LED characteristics
intent.putExtra("ctrl2_service_id", gattCharacteristic.getService().getUuid().toString());//UUID of my LED service
startActivity(intent);
}
The part I fail is the function that I try to turn LED on.
public boolean turnLEDon()
{
byte[] value = {(byte)1};
characteristicCTRL2.setValue(value);//This is the line I failed
boolean status = mBluetoothLeService.mBluetoothGatt.writeCharacteristic(characteristicCTRL2);
return status;
};
The following is my complete code of trying to manipulate two characteristics at the same interface.
package com.example.android.bluetoothlegatt;
public class AutoConnectActivity extends Activity {
private BluetoothGattCharacteristic characteristic;
private BluetoothGattCharacteristic characteristicCTRL2;
private String address;
private UUID serviceId;
private UUID charId;
private UUID ctrl2ServiceId;
private UUID ctrl2CharId;
private TextView debugText;
private Button startBtn;
private Button stopBtn;
private Button ctrlStartBtn;
private Button ctrlStopBtn;
private Timer timer = new Timer();
private boolean started = false;
private ArrayAdapter<String> adapter;
private String Entry;
private File file;
private boolean check= true;
private BluetoothLeService mBluetoothLeService;
public boolean turnLEDon()
{
byte[] value = {(byte)1};
characteristicCTRL2.setValue(value);//This is the line I failed
boolean status = mBluetoothLeService.mBluetoothGatt.writeCharacteristic(characteristicCTRL2);
return status;
};
public boolean turnLEDoff()
{
byte[] value = {(byte)0};
characteristicCTRL2.setValue(value);
boolean status = mBluetoothLeService.mBluetoothGatt.writeCharacteristic(characteristicCTRL2);
return !status;
};
private TimerTask timerTask = new TimerTask() {
#Override
public void run() {
mBluetoothLeService.connect(address);
}
};
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
mBluetoothLeService.connect(address);
List<BluetoothGattService> list = mBluetoothLeService.getSupportedGattServices();
for(BluetoothGattService s : list){
if(s.getUuid().compareTo(serviceId) == 0){
if (check==true) {
characteristic = s.getCharacteristic(charId);
mBluetoothLeService.disconnect();
}
return;
}
if(s.getUuid().compareTo(ctrl2ServiceId) == 0){
if(check==false) {
characteristicCTRL2 = s.getCharacteristic(ctrl2CharId);
}
return;
}
}
mBluetoothLeService.disconnect();
Log.e(TAG, "not find device");
debugText.setText("not find device");
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
debugText.setText(action);
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
// if temperature measurement
if (check==true){
mBluetoothLeService.readCharacteristic(characteristic);}
// if control LED
if(check==false){
mBluetoothLeService.readCharacteristic(characteristicCTRL2);
turnLEDon();
}
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action))
{
if (check==false) {
String CTRL_Status = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
adapter.add("CTRL Status: " + CTRL_Status + " " + new Date(System.currentTimeMillis()));
turnLEDoff();
mBluetoothLeService.disconnect();
}
if(check==true) {
String temperature = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
adapter.add("Temperature: " + temperature + "°C " + new Date(System.currentTimeMillis()));
Entry = address + "," + new Date(System.currentTimeMillis()).toString() + "," + temperature.toString() + "\n";
try {
FileOutputStream out = new FileOutputStream(file, true);
out.write(Entry.getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mBluetoothLeService.disconnect();
}
}
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autoconnect);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
address = intent.getStringExtra("address");
serviceId = UUID.fromString(intent.getStringExtra("service_id"));
charId = UUID.fromString(intent.getStringExtra("character_id"));
ctrl2ServiceId = UUID.fromString(intent.getStringExtra("ctrl2_service_id"));
Log.e(TAG, " CTRL2 SERVICE: " + ctrl2ServiceId);
ctrl2CharId = UUID.fromString(intent.getStringExtra("ctrl2_character_id"));
Log.e(TAG, " CTRL2 CHARAC: " + ctrl2CharId);
((TextView)findViewById(R.id.address_txt)).setText(address);
((TextView)findViewById(R.id.service_txt)).setText(serviceId.toString());
((TextView)findViewById(R.id.char_txt)).setText(charId.toString());
debugText = (TextView)findViewById(R.id.debug_txt);
startBtn = (Button)findViewById(R.id.start_btn);
stopBtn = (Button)findViewById(R.id.stop_btn);
ctrlStartBtn = (Button)findViewById(R.id.ctrl_start_btn);
ctrlStopBtn = (Button)findViewById(R.id.ctrl_stop_btn);
ListView listView = (ListView)findViewById(R.id.result_list);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(started) return;
started = true;
check=true;
//External Storage
String state;
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File root = Environment.getExternalStorageDirectory();
File Dir = new File(root.getAbsolutePath() + "/MeasurementDataFile");
if (!Dir.exists()) {
Dir.mkdir();
}
file = new File(Dir, "Temperature.csv");
}
if (check==true){
timer.schedule(timerTask, 0, 1000 * 5); }
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!started) return;
started = false;
check=true;
timer.cancel();
}
});
ctrlStartBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mBluetoothLeService.connect(address);
check=false;
if(started) return;
started = true;
Toast.makeText (getBaseContext(), "Turn CTRL 1 ON", Toast.LENGTH_SHORT).show();
Log.e(TAG, " On?: " + turnLEDon());
}
});
ctrlStopBtn.setOnClickListener(new View.OnClickListener() {
//mBluetoothLeService.connect(address);
#Override
public void onClick(View v) {
if(!started) return;
started = false;
check=false;
Log.e(TAG, " Off?: " + turnLEDoff());
Toast.makeText (getBaseContext(), "Turn CTRL 1 OFF", Toast.LENGTH_SHORT).show();
}
});
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, DeviceControlActivity.makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(address);
Log.d(TAG, "Connect request result=" + result);
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
}
All BLE calls are asynchronous. This is really pain-in-neck, but we have what we have. So you cannot just write:
{
boolean status = writeCharacteristic(characteristic);
return status;
}
and hope all will be ok. In this case, you obtain a result of the writeCharacteristic instruction only, but not the real write operation result! For the last, you need to register the part of your code as BluetoothGattCallback descendant and read OnCharacteristicWrite event, where you can really know the result of your write operation.
All BLE read-write operations should be done in a strict one-by-one sequence and from main app thread only.
Different devices have different capabilities and productivity, so you can obtain different results - IMHO, this is less strange, than Google's decision to realize BLE stack in this manner :)
Pretty BLE guide for Android can be found here: https://droidcon.de/sites/global.droidcon.cod.newthinking.net/files/media/documents/practical_bluetooth_le_on_android_0.pdf
Edit
The link above is broken but the other one can be found here:
https://speakerdeck.com/erikhellman/practical-bluetooth-low-energy-on-android

Android BLE command sending is not working

I am struggling through one strange issue that is Command send from android device to BLE dongle. Here i have two buttons Button1 and Button2. On click of each button i am trying to send to different command to BLE dongle. Elaboration of issue is below:
Fragment launch with two buttons Button1 and Button2
Click on Button1
Command send to BLE dongle sucessfully
Then clicked in Button2 command doesn't send to BLE.
Again re-run and Fragment launch now i clicked Buttons2
Command send successfully
Them clicked on Button1 command doesn't send.
*
Concussion- Command send only on first click of first button.
*
Now here is code which i have used
Below is code i am calling at from onCreateView() of Fragment to initialize the services and Broadcast receiver.
if(SingleTon.getInstance().getDeviceAddress() !=null && SingleTon.getInstance().getDeviceName() != null) {
if(!SingleTon.getInstance().isLEServiceGattInit())
settingObj.deviceControl(getActivity(), SingleTon.getInstance().getDeviceAddress(), SingleTon.getInstance().getDeviceName());
}
Now methods which will get call form above code-
public void deviceControl(Context context,String deviceAddress, String devicename ){
progressServices = new ProgressDialog(context);
progressServices = ProgressDialog.show(context, "",
"Looking for Services....", true);
this.mcontext = context;
this.mDeviceAddress = deviceAddress;
this.mDeviceName = devicename;
initServices();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if(progressServices.isShowing()) {
progressServices.dismiss();
Toast.makeText(mcontext,"Issue in BLE, not able to advertise Services/UUIDs.",Toast.LENGTH_LONG).show();
}
}
}, 6000);
}
private void initServices(){
Intent gattServiceIntent = new Intent(mcontext, BluetoothLeService.class);
mcontext.bindService(gattServiceIntent, mServiceConnection, getActivity().BIND_AUTO_CREATE);
mcontext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
}
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize");
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
SingleTon.getInstance().setLEServiceGattInit(false);
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// Show all the supported services and characteristics on the user interface.
displayGattServices(mBluetoothLeService.getSupportedGattServices());
SingleTon.getInstance().setmBluetoothLeService(mBluetoothLeService);
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
}
}
};
private void displayGattServices(List<BluetoothGattService> gattServices) {
if (gattServices == null) return;
String uuid;
String unknownServiceString = "Unknown Services";
String unknownCharaString = "Unknown Characteristic";
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<>();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
= new ArrayList<>();
mGattCharacteristics = new ArrayList<>();
// Loops through available GATT Services.
String LIST_NAME = "NAME";
String LIST_UUID = "UUID";
for (BluetoothGattService gattService : gattServices) {
uuid = gattService.getUuid().toString();
if(uuid.contains("ff02")){
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
if (gattCharacteristic.getUuid().equals(UUID.fromString("0000c002-0000-1000-8000-00805f9b34fb"))) {
SingleTon.getInstance().setListWriteCharecteristic(gattCharacteristic);
progressServices.dismiss();
SingleTon.getInstance().setLEServiceGattInit(true);
}
}
}
}
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentFilter;
}
Now below is code which we are calling for command send on each button click.
btn_head_up.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
sendHexCommand(CommandListHex.Hex20BIT_ACT_HEAD_UP);
return true;
}
});
private void sendHexCommand(String cmd){
if(SingleTon.getInstance().getDeviceAddress() !=null && SingleTon.getInstance().getDeviceName() != null) {
settingObj.sendCommand(cmd, SingleTon.getInstance().getListWriteCharecteristic(), SingleTon.getInstance().getmBluetoothLeService());
} else{
showDialog(getActivity(), getResources().getString(R.string.dialogtitle), "First do configuration for Bluetooth");
}
}
And now finally code to send command
public void sendCommand(String Control_INST, ArrayList<BluetoothGattCharacteristic> charFromSinglonton ,
BluetoothLeService bleGATTService){
for(BluetoothGattCharacteristic gattChar :charFromSinglonton) {
if (charFromSinglonton != null) {
final BluetoothGattCharacteristic characteristic = gattChar;
boolean status = bleGATTService.writeCharacteristic(characteristic, hexStringToByteArray(Control_INST));
if (status) {
SingleTon.getInstance().setCorrectWriteGattCharecteristic(gattChar);
}
}
}
}
Thanks in advance to all.
If you click the same button twice(like first button) what will happen? Send command twice or only one time ?

Categories

Resources