android BLE

If you are an electronics enthusiast, and also fond of programming, I would be very glad to share with you an Android BLE application development method, so you can integrate the phone and MCU to do some more interesting things. Right now we begin to explain how to develop an Android BLE application, and you can also refer to the official Google tutorial . This guide is a packed tutorial, which enables you to build your Android BLE application more easily and more quickly. Of course, I’ll upload my source code for everyone to share it and you can also refer to the official sample sdk/samples/android-18/legacy/BluetoothLeGatt.

1. Create a new Android project

Open Eclipse,File->New->Android Application Project,and then fill the Application name in the Application Name edit box, for example, BleExample,or others. Minimum Required SDK selects API18:Android 4.3,and Target SDK also selects API18:Android 4.3,as buletooth 4.0 must be with Android 4.3edition or above. Others default unchanged and please continue clicking the Next button until Finish button appears,and then click the Finish button.

2. Add the permissions and services

Add the below code in the manifest file:


1
2
3
4
5
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

<service android:name="com.elecfreaks.ble.BluetoothLeService" android:enabled="true"/>

3. Create the ListView item layout file

Aiming to display each content of ListView, here we use customization(defining by yourself), so that each ListView can show more content,item_list.xml is demonstrated as below:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"    
    >
    <TextView android:id="@+id/textViewDevName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="24dp"/>
    <TextView android:id="@+id/textViewDevAddress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#FF0000"
            android:textSize="12dp"/>
</LinearLayout>
Copy the source code of BleExample /com.elecfreaks.ble to your project src directory,and then open the file with error prompt, pressing the shift+ctrl+O keys.

4. Modify activity_main.xml, increasing scanButton and bleDeviceListView

Increased contents are shown as below:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    <Button
        android:id="@+id/scanButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="scanOnClick"
        android:text="scan" />

    <ListView
        android:id="@+id/bleDeviceListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/scanButton"
        android:layout_below="@+id/scanButton"
        android:layout_above="@+id/sendButton"
         >
    </ListView>

5. In MainActivity.java, add scanButton mothod of responding to events


1
2
3
(onClick="scanOnClick")
      public void scanOnClick(final View v){
}

6. Add member for MainActivity


1
2
3
4
5
6
  private Button scanButton;
  private ListView bleDeviceListView;
  private BLEDeviceListAdapter listViewAdapter;

  private BluetoothHandler bluetoothHandler;
  private boolean isConnected;
  1. 7. Set member value in MainActivity.onCreate


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  scanButton = (Button)findViewById(R.id.scanButton);
  bleDeviceListView = (ListView)findViewById(R.id.bleDeviceListView);
  listViewAdapter = new BLEDeviceListAdapter(this);

  bluetoothHandler = new BluetoothHandler(this);
        bluetoothHandler.setOnConnectedListener(new OnConnectedListener() {

    @Override
    public void onConnected(boolean isConnected) {
      // TODO Auto-generated method stub
      setConnectStatus(isConnected);
    }
  });
  bluetoothHandler.setOnRecievedDataListener(new  OnRecievedDataListener() {

    @Override
    public void onRecievedData(byte[] bytes) {
      // TODO Auto-generated method stub
      System.out.printf("REC:");
      for(byte b:bytes)
        System.out.printf("%02X ", b);
      System.out.printf("\n");
    }
  });

8. Adding setConnectStatus mothod


1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void setConnectStatus(boolean isConnected){
  this.isConnected = isConnected;
  if(isConnected){
    showMessage("Connection successful");
    scanButton.setText("break");
  }else{
    bluetoothHandler.onPause();
       bluetoothHandler.onDestroy();
       scanButton.setText("scan");
  }
}
private void showMessage(String str){
  Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}

9. Adding content in scanOnClick


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
if(!isConnected){
  bleDeviceListView.setAdapter(bluetoothHandler.getDeviceListAdapter());
  bleDeviceListView.setOnItemClickListener(new OnItemClickListener() {

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    String buttonText = (String) ((Button)v).getText();
    if(buttonText.equals("scanning")){
      showMessage("scanning...");
      return ;
    }
    BluetoothDevice device = bluetoothHandler.getDeviceListAdapter().getItem(position).device;
      // connect
      bluetoothHandler.connect(device.getAddress());
    }
  });
  bluetoothHandler.setOnScanListener(new OnScanListener() {
    @Override
    public void onScanFinished() {
      // TODO Auto-generated method stub
      ((Button)v).setText("scan");
      ((Button)v).setEnabled(true);
    }
    @Override
    public void onScan(BluetoothDevice device, int rssi, byte[] scanRecord) {}
  });
  ((Button)v).setText("scanning");
  ((Button)v).setEnabled(false);
  bluetoothHandler.scanLeDevice(true);
}else{
  setConnectStatus(false);
}

10. Send data


1
2
3
byte[] data = new byte[1];
data[0] = 0x02;
bluetoothHandler.sendData(data);

11. Receive data

Upon receiving data, the mothod of OnRecievedDataListener.onRecievedData(byte[] bytes) set from bluetoothHandler.setOnRecievedDataListener()OnRecievedDataListener.onRecievedData(byte[] bytes) would be used,and bytes means received data

12. Send data to MCU via protocol.(Use BLUNO from ElecFreaks)

In src directory, create Transmitter.java, adding the constructed function with two parameters as below:


1
2
3
4
5
6
7
8
public Transmitter(Context context, BluetoothHandler bluetoothHandler){
  this.context = context;
  this.mBluetoothHandler = bluetoothHandler;
}

private void sendData(byte[] bytes){
  mBluetoothHandler.sendData(bytes);
}

13. Receive MCU data via protocol.

MCU data receiving and sending protocol uses JSON packet,and the format is {“T”:your value, “V”:your value, …}. Of course you can define other values. Create the MyArray.java in src directory,aiming to connecting two arrays. The code was shown as below:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MyArray {

  static public byte[] arrayCat(byte[] buf1,byte[] buf2){
      byte[] bufret=null;
      int len1 = 0;
      int len2 = 0;
      if(buf1 != null)
        len1 = buf1.length;
      if(buf2 != null)
        len2 = buf2.length;
      if(len1+len2 > 0)
        bufret = new byte[len1+len2];
      if(len1 > 0)
        System.arraycopy(buf1, 0, bufret, 0, len1);
      if(len2 > 0)
        System.arraycopy(buf2, 0, bufret, len1, len2);
      return bufret;
    }
}

Copy the protocol.java in my sample code to src directory Adding member


1
private Protocol protocol;

From onCreate(),delete:


1
bluetoothHandler.setOnRecievedDataListener();

Adding:


1
2
protocol = new Protocol(this, new Transmitter(this, bluetoothHandler));
protocol.setOnReceivedDataListener(recListener);

Adding member in MainActivity:


1
2
3
4
5
6
private static final boolean INPUT = false;
private static final boolean OUTPUT = true;
private static final boolean LOW = false;
private static final boolean HIGH = true;
private boolean digitalVal[];
private int analogVal[];

Initializing in onCreate:


1
2
digitalVal = new boolean[14];
analogVal = new int[14];

Adding a member:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
private OnReceivedRightDataListener recListener = new OnReceivedRightDataListener() {

  @Override
  public int onReceivedData(String str) {
    // TODO Auto-generated method stub
    try {
      JSONObject readJSONObject = new JSONObject(str);
      int type = readJSONObject.getInt("T");
      int value = readJSONObject.getInt("V");

      switch(type){
        case Protocol.ANALOG:{
          int pin = readJSONObject.getInt("P");
          analogVal[pin] = value;
        }break;
        case Protocol.DIGITAL:{
          int pin = readJSONObject.getInt("P");
          digitalVal[pin] = (value>0)?HIGH:LOW;
        }break;
        case Protocol.TEMPERATURE:{
          float temperature = ((float)value)/100;
        }break;
        case Protocol.HUMIDITY:{
          float humidity = ((float)value)/100;
        }break;
        default:break;
      }
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return 0;
  }
};

14. Use protocol to send data


1
protocol.writeAnalogData(9, 20); protocol.writeDigitalData(3, 1);

15. Use protocol to receive data


1
protocol.readAnalogDataCommand(9); protocol.readDigitalDataCommand(3);

Note: Returned data is received by recListener

16. MCU port protocol(arduino)

Refer to the sample code of AndroidIOControl provided by me

17. If you need more information, please refer to our website

 

VN:F [1.9.13_1145]
Rating: 5.8/10 (12 votes cast)
VN:F [1.9.13_1145]
Rating: +2 (from 2 votes)
Android BLE User Guide, 5.8 out of 10 based on 12 ratings
dany

Author dany

More posts by dany

Join the discussion 4 Comments

  • Roel says:

    Nice that you keep “// TODO Auto-generated method stub” in your source code…

    [Reply]

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.13_1145]
    Rating: 0 (from 0 votes)
  • Asher Holloman says:

    I got this running on my device, but while testing BLE connectivity it fails to find and connect to BLE equipped devices. The app runs, but when you hit scan it just scans for a bit and then stops and fails to find any devices. Any help would be much appreciated!!!!! Thanks

    [Reply]

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.13_1145]
    Rating: 0 (from 0 votes)
  • SAID says:

    Hi,I’m trying to develop an android app that tracks data on a BLEduino and i wondor if there is code examples anywhere.This article helps already a lot!!

    [Reply]

    Sana Ali Reply:

    Hi,On running this code I’ m getting an error on My AVD.”Your device not support BLE”. What should I do?Kindly help.

    [Reply]

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.13_1145]
    Rating: 0 (from 0 votes)

Leave a Reply