├── .gitignore ├── .google └── packaging.yaml ├── Application ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ ├── advertising_animation.html │ ├── discovering_animation.html │ ├── motion_tracker.gif │ └── signal.gif │ ├── java │ └── com │ │ └── example │ │ └── android │ │ ├── ble │ │ ├── BLEAdvertiseCallback.java │ │ ├── BLEAdvertisingActivity.java │ │ ├── BLECentralChatEvents.java │ │ ├── BLECentralHelper.java │ │ ├── BLEChatEvents.java │ │ ├── BLEChatProfile.java │ │ ├── BLEDiscoverCallback.java │ │ ├── BLEDiscoveringActivity.java │ │ ├── BLEGattConstants.java │ │ ├── BLEMode.java │ │ ├── BLEPeripheralChatEvents.java │ │ └── BLEPeripheralHelper.java │ │ ├── bluetoothchat │ │ ├── BluetoothChatFragment.java │ │ ├── BluetoothChatService.java │ │ ├── Constants.java │ │ ├── DeviceListActivity.java │ │ └── MainActivity.java │ │ └── common │ │ ├── activities │ │ └── SampleActivityBase.java │ │ └── logger │ │ ├── Log.java │ │ ├── LogFragment.java │ │ ├── LogNode.java │ │ ├── LogView.java │ │ ├── LogWrapper.java │ │ └── MessageOnlyLogFilter.java │ └── res │ ├── drawable-hdpi │ ├── ic_action_device_access_bluetooth_searching.png │ ├── ic_launcher.png │ └── tile.9.png │ ├── drawable-mdpi │ ├── ic_action_device_access_bluetooth_searching.png │ └── ic_launcher.png │ ├── drawable-xhdpi │ ├── ic_action_device_access_bluetooth_searching.png │ └── ic_launcher.png │ ├── drawable-xxhdpi │ ├── ic_action_device_access_bluetooth_searching.png │ └── ic_launcher.png │ ├── layout-w720dp │ └── activity_main.xml │ ├── layout │ ├── activity_ble_advertising.xml │ ├── activity_ble_discovering.xml │ ├── activity_device_list.xml │ ├── activity_main.xml │ ├── device_name.xml │ ├── fragment_bluetooth_chat.xml │ └── message.xml │ ├── menu │ ├── bluetooth_chat.xml │ └── main.xml │ ├── values-sw600dp │ ├── template-dimens.xml │ └── template-styles.xml │ ├── values-v11 │ └── template-styles.xml │ ├── values-v21 │ ├── base-colors.xml │ └── base-template-styles.xml │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── base-strings.xml │ ├── dimens.xml │ ├── fragmentview_strings.xml │ ├── strings.xml │ ├── template-dimens.xml │ └── template-styles.xml ├── CONTRIB.md ├── CONTRIBUTING.md ├── LICENSE ├── README-origin.md ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── screenshots ├── 1-launch.png ├── 2-devices.png ├── 3-chat.png └── icon-web.png └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | #built application files 2 | *.apk 3 | *.ap_ 4 | # files for the dex VM 5 | *.dex 6 | 7 | # Java class files 8 | *.class 9 | 10 | # generated files 11 | bin/ 12 | gen/ 13 | 14 | # Local configuration file (sdk path, etc) 15 | local.properties 16 | 17 | # Windows thumbnail db 18 | Thumbs.db 19 | 20 | # OSX files 21 | .DS_Store 22 | 23 | # Eclipse project files 24 | .classpath 25 | .project 26 | 27 | # Android Studio 28 | *.iml 29 | .idea 30 | #.idea/workspace.xml - remove # and delete .idea if it better suit your needs. 31 | .gradle 32 | build/ 33 | 34 | #NDK 35 | obj/ 36 | -------------------------------------------------------------------------------- /.google/packaging.yaml: -------------------------------------------------------------------------------- 1 | 2 | # GOOGLE SAMPLE PACKAGING DATA 3 | # 4 | # This file is used by Google as part of our samples packaging process. 5 | # End users may safely ignore this file. It has no relevance to other systems. 6 | --- 7 | status: PUBLISHED 8 | technologies: [Android] 9 | categories: [Connectivity] 10 | languages: [Java] 11 | solutions: [Mobile] 12 | github: android-BluetoothChat 13 | level: ADVANCED 14 | icon: screenshots/icon-web.png 15 | apiRefs: 16 | - android:android.bluetooth.BluetoothAdapter 17 | - android:android.bluetooth.BluetoothDevice 18 | - android:android.bluetooth.BluetoothServerSocket 19 | - android:android.bluetooth.BluetoothSocket 20 | license: apache2 21 | -------------------------------------------------------------------------------- /Application/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | buildscript { 3 | repositories { 4 | jcenter() 5 | } 6 | 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.1.0' 9 | } 10 | } 11 | 12 | apply plugin: 'com.android.application' 13 | 14 | repositories { 15 | jcenter() 16 | } 17 | 18 | dependencies { 19 | compile "com.android.support:support-v4:23.0.0" 20 | compile "com.android.support:gridlayout-v7:23.0.0" 21 | compile "com.android.support:cardview-v7:23.0.0" 22 | } 23 | 24 | // The sample build uses multiple directories to 25 | // keep boilerplate and common code separate from 26 | // the main sample code. 27 | List dirs = [ 28 | 'main', // main sample code; look here for the interesting stuff. 29 | 'common', // components that are reused by multiple samples 30 | 'template'] // boilerplate code that is generated by the sample template process 31 | 32 | android { 33 | compileSdkVersion 23 34 | buildToolsVersion "23.0.0" 35 | 36 | defaultConfig { 37 | minSdkVersion 21 38 | targetSdkVersion 23 39 | } 40 | 41 | compileOptions { 42 | sourceCompatibility JavaVersion.VERSION_1_7 43 | targetCompatibility JavaVersion.VERSION_1_7 44 | } 45 | 46 | sourceSets { 47 | main { 48 | dirs.each { dir -> 49 | java.srcDirs "src/${dir}/java" 50 | res.srcDirs "src/${dir}/res" 51 | } 52 | } 53 | androidTest.setRoot('tests') 54 | androidTest.java.srcDirs = ['tests/src'] 55 | 56 | } 57 | 58 | } 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /Application/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 16 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 32 | 33 | 38 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 53 | 54 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Application/src/main/assets/advertising_animation.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Application/src/main/assets/discovering_animation.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Application/src/main/assets/motion_tracker.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/assets/motion_tracker.gif -------------------------------------------------------------------------------- /Application/src/main/assets/signal.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/assets/signal.gif -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEAdvertiseCallback.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | import android.bluetooth.BluetoothDevice; 4 | 5 | /** 6 | * Created by jgomez on 2/05/16. 7 | */ 8 | public interface BLEAdvertiseCallback { 9 | void onInitSuccess(); 10 | void onInitFailure(String message); 11 | void onClientConnect(BluetoothDevice device); 12 | void onInfo(String info); 13 | void onError(String error); 14 | } 15 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEAdvertisingActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | import android.app.Activity; 4 | import android.bluetooth.BluetoothDevice; 5 | import android.content.Intent; 6 | import android.os.Bundle; 7 | import android.support.v4.app.FragmentActivity; 8 | import android.view.KeyEvent; 9 | import android.webkit.WebView; 10 | import android.widget.TextView; 11 | 12 | import com.example.android.bluetoothchat.R; 13 | 14 | public class BLEAdvertisingActivity extends FragmentActivity { 15 | 16 | public static String EXTRA_CLIENT_NAME = "ble_client_name"; 17 | 18 | BLEPeripheralHelper mBleChat = BLEPeripheralHelper.getInstance(); 19 | 20 | @Override 21 | protected void onCreate(Bundle savedInstanceState) { 22 | super.onCreate(savedInstanceState); 23 | setContentView(R.layout.activity_ble_advertising); 24 | WebView animation = (WebView)findViewById(R.id.webView2); 25 | animation.loadUrl("file:///android_asset/advertising_animation.html"); 26 | mBleChat.register(mBLEAdvCallback); 27 | mBleChat.init(getApplicationContext()); 28 | } 29 | 30 | public void setConsoleText(String text){ 31 | TextView t = (TextView)findViewById(R.id.adv_text_console); 32 | t.setText(text); 33 | } 34 | 35 | @Override 36 | public boolean onKeyDown(int keyCode, KeyEvent event) 37 | { 38 | if ((keyCode == KeyEvent.KEYCODE_BACK)) 39 | { 40 | mBleChat.stopAdvertising(); 41 | finish(); 42 | } 43 | return super.onKeyDown(keyCode, event); 44 | } 45 | 46 | private BLEAdvertiseCallback mBLEAdvCallback = new BLEAdvertiseCallback(){ 47 | 48 | @Override 49 | public void onInitSuccess() { 50 | mBleChat.startAdvertising(); 51 | } 52 | 53 | @Override 54 | public void onInitFailure(String message) { 55 | setConsoleText(message); 56 | } 57 | 58 | @Override 59 | public void onClientConnect(BluetoothDevice device){ 60 | // Create the result Intent and include the MAC address 61 | Intent intent = new Intent(); 62 | //intent.putExtra(EXTRA_CLIENT_NAME, device.getName()); 63 | 64 | // Set result and finish this Activity 65 | setResult(Activity.RESULT_OK, intent); 66 | mBleChat.unregister(mBLEAdvCallback); 67 | //mBleChat.stopAdvertising(); 68 | finish(); 69 | } 70 | 71 | @Override 72 | public void onInfo(String info){ 73 | setConsoleText(info); 74 | } 75 | 76 | @Override 77 | public void onError(String error){ 78 | setResult(Activity.RESULT_CANCELED); 79 | finish(); 80 | } 81 | }; 82 | } 83 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLECentralChatEvents.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | /** 4 | * Created by jgomez on 29/04/16. 5 | */ 6 | public interface BLECentralChatEvents extends BLEChatEvents { 7 | int MTU_CHANGE_SUCCEED = 0; 8 | int MTU_CHANGE_FAILED = 1; 9 | void onConnect(); 10 | void onDisconnect(); 11 | void onVersion(String version); 12 | void onDescription(String description); 13 | void onRfcommConnect(); 14 | void onMtuChanged(int status, int newMtu); 15 | } 16 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLECentralHelper.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | import android.bluetooth.BluetoothAdapter; 4 | import android.bluetooth.BluetoothDevice; 5 | import android.bluetooth.BluetoothGatt; 6 | import android.bluetooth.BluetoothGattCallback; 7 | import android.bluetooth.BluetoothGattCharacteristic; 8 | import android.bluetooth.BluetoothGattService; 9 | import android.bluetooth.BluetoothManager; 10 | import android.bluetooth.BluetoothProfile; 11 | import android.bluetooth.BluetoothSocket; 12 | import android.bluetooth.le.ScanCallback; 13 | import android.bluetooth.le.ScanFilter; 14 | import android.bluetooth.le.ScanResult; 15 | import android.bluetooth.le.ScanSettings; 16 | import android.content.BroadcastReceiver; 17 | import android.content.Context; 18 | import android.content.Intent; 19 | import android.content.IntentFilter; 20 | import android.content.pm.PackageManager; 21 | import android.net.Uri; 22 | import android.os.Handler; 23 | import android.os.ParcelUuid; 24 | import android.util.Log; 25 | 26 | import java.io.ByteArrayOutputStream; 27 | import java.io.FileNotFoundException; 28 | import java.io.IOException; 29 | import java.io.InputStream; 30 | import java.io.OutputStream; 31 | import java.util.ArrayList; 32 | import java.util.Arrays; 33 | import java.util.List; 34 | import java.util.Random; 35 | import java.util.UUID; 36 | import java.util.concurrent.RunnableFuture; 37 | 38 | 39 | /** 40 | * This class will manage the Bluetooth LE Central stuff 41 | * A Central BLE device is a device which can connect to another Peripheral device that is 42 | * advertising services. So it's basically a client. 43 | * 44 | * It communicates with the outer space via events like: 45 | * * BLEDiscoverCallback 46 | * * BLECentralChatEvents 47 | * 48 | * Use init() no initialize the class 49 | * 50 | */ 51 | public class BLECentralHelper { 52 | 53 | private static final String TAG = "BLECentralHelper"; 54 | 55 | // Name for the SDP record when creating server socket 56 | private static final String NAME_SECURE = "BluetoothLEChatSecure"; 57 | private static final String NAME_INSECURE = "BluetoothLEChatInsecure"; 58 | // Unique UUID for this application 59 | private static final UUID MY_UUID_SECURE = 60 | UUID.fromString("caa8f277-6b87-49fb-a11b-ab9c9dacbd44"); 61 | private static final UUID MY_UUID_INSECURE = 62 | UUID.fromString("83769a57-e930-4496-8ece-fec16420c77c"); 63 | 64 | private static final int MAX_RETRIES = 5; 65 | 66 | private BluetoothManager mBluetoothManager; 67 | private BluetoothAdapter mBluetoothAdapter; 68 | private BluetoothGatt mConnectedGatt; 69 | /* Test RFCOMMSocket connection */ 70 | private BluetoothSocket mSocket; 71 | private String mRfcommSocketAddress; 72 | private BLEDiscoverCallback mBleDiscoveryCallback; 73 | private BLECentralChatEvents mBleChatEvents; 74 | 75 | private Handler mHandler = new Handler(); 76 | 77 | private Context mContext; 78 | 79 | private static BLECentralHelper instance = new BLECentralHelper(); 80 | private BLECentralHelper(){} 81 | public static BLECentralHelper getInstance(){ 82 | if(instance == null){ 83 | synchronized (BLECentralHelper.class){ 84 | if(instance == null){ 85 | instance = new BLECentralHelper(); 86 | } 87 | } 88 | } 89 | return instance; 90 | } 91 | 92 | public void init(Context context, BLEDiscoverCallback bleCallback){ 93 | mContext = context; 94 | mBleDiscoveryCallback = bleCallback; 95 | if( context == null){ 96 | mBleDiscoveryCallback.onInitFailure("Invalid Context!"); 97 | return; 98 | } 99 | mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); 100 | mBluetoothAdapter = mBluetoothManager.getAdapter(); 101 | if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()){ 102 | mBleDiscoveryCallback.onInitFailure("Bluetooth not supported in this device!!"); 103 | return; 104 | } 105 | 106 | if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { 107 | mBleDiscoveryCallback.onInitFailure("Bluetooth LE is not supported in this devices!!"); 108 | return; 109 | } 110 | 111 | 112 | mBleDiscoveryCallback.onInitSuccess(); 113 | } 114 | 115 | /** 116 | * This is a passive action, it will listen advertisements from other peripheral devices 117 | */ 118 | public void startScan() { 119 | 120 | ScanFilter scanFilter = new ScanFilter.Builder() 121 | .setServiceUuid(new ParcelUuid(BLEChatProfile.SERVICE_UUID)) 122 | .build(); 123 | ArrayList filters = new ArrayList(); 124 | filters.add(scanFilter); 125 | 126 | ScanSettings settings = new ScanSettings.Builder() 127 | .setScanMode(ScanSettings.SCAN_MODE_BALANCED) 128 | .build(); 129 | mBluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, mScanCallback); 130 | } 131 | 132 | public void stopScan() { 133 | mBluetoothAdapter.getBluetoothLeScanner().stopScan(mScanCallback); 134 | } 135 | 136 | private ScanCallback mScanCallback = new ScanCallback() { 137 | @Override 138 | public void onScanResult(int callbackType, ScanResult result) { 139 | Log.d(TAG, "onScanResult"); 140 | processResult(result); 141 | } 142 | 143 | @Override 144 | public void onBatchScanResults(List results) { 145 | Log.d(TAG, "onBatchScanResults: "+results.size()+" results"); 146 | for (ScanResult result : results) { 147 | processResult(result); 148 | } 149 | } 150 | 151 | @Override 152 | public void onScanFailed(int errorCode) { 153 | Log.w(TAG, "LE Scan Failed: "+errorCode); 154 | } 155 | 156 | private void processResult(ScanResult result) { 157 | BluetoothDevice device = result.getDevice(); 158 | Log.i(TAG, "New LE Device: " + device.getName() + " @ " + result.getRssi()); 159 | mBleDiscoveryCallback.onScanResult(device, result.getRssi()); 160 | } 161 | }; 162 | 163 | /* 164 | * Connect to a Bluetooth device 165 | * 166 | * @param context 167 | * @param device 168 | * @param events 169 | */ 170 | public void connect(Context context, BluetoothDevice device, BLECentralChatEvents events){ 171 | mBleChatEvents = events; 172 | mConnectedGatt = device.connectGatt(context, false, mGattCallback); 173 | } 174 | 175 | /** 176 | * Will try to connect to a RFCOMMSocket previously announced by the Peripheral device 177 | * WARNING: This is just a test. It may fail... 178 | * 179 | * 180 | */ 181 | private void connect2RfcommSocket(){ 182 | IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 183 | mContext.registerReceiver(mReceiver, filter); 184 | // Register for broadcasts when discovery has finished 185 | filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 186 | mContext.registerReceiver(mReceiver, filter); 187 | mBluetoothAdapter.startDiscovery(); 188 | 189 | } 190 | 191 | private BroadcastReceiver mReceiver = new BroadcastReceiver() { 192 | @Override 193 | public void onReceive(Context context, Intent intent) { 194 | String action = intent.getAction(); 195 | // When discovery finds a device 196 | if (BluetoothDevice.ACTION_FOUND.equals(action)) { 197 | // Get the BluetoothDevice object from the Intent 198 | BluetoothDevice classicBtDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 199 | if (mRfcommSocketAddress.compareTo(classicBtDevice.getAddress()) == 0) { 200 | try { 201 | mSocket = classicBtDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE); 202 | mSocket.connect(); 203 | mBleChatEvents.onRfcommConnect(); 204 | } catch (IOException e) { 205 | try { 206 | mSocket.close(); 207 | } catch (IOException e2) { 208 | mBleChatEvents.onConnectionError(e2.toString()); 209 | } 210 | mBleChatEvents.onConnectionError(e.toString()); 211 | } 212 | } 213 | // When discovery is finished, change the Activity title 214 | } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 215 | 216 | } 217 | } 218 | }; 219 | 220 | public BluetoothGattCallback mGattCallback = new BluetoothGattCallback(){ 221 | @Override 222 | public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { 223 | super.onConnectionStateChange(gatt, status, newState); 224 | Log.d(TAG, "onConnectionStateChange " 225 | +BLEChatProfile.getStatusDescription(status)+" " 226 | +BLEChatProfile.getStateDescription(newState)); 227 | 228 | if(status == BluetoothGatt.GATT_SUCCESS) { 229 | if (newState == BluetoothProfile.STATE_CONNECTED) { 230 | gatt.discoverServices(); 231 | } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { 232 | mHandler.post(new Runnable() { 233 | @Override 234 | public void run() { 235 | mBleChatEvents.onDisconnect(); 236 | } 237 | }); 238 | 239 | } 240 | }else{ 241 | final int finalStatus = status; 242 | mHandler.post(new Runnable() { 243 | @Override 244 | public void run() { 245 | mBleChatEvents.onConnectionError("Connection state error! : Error = " + finalStatus); 246 | } 247 | }); 248 | 249 | } 250 | } 251 | 252 | @Override 253 | public void onServicesDiscovered(BluetoothGatt gatt, int status) { 254 | super.onServicesDiscovered(gatt, status); 255 | Log.d(TAG, "onServicesDiscovered:"); 256 | 257 | for (BluetoothGattService service : gatt.getServices()) { 258 | Log.d(TAG, "Service: "+service.getUuid()); 259 | if (BLEChatProfile.SERVICE_UUID.equals(service.getUuid())) { 260 | gatt.readCharacteristic(service.getCharacteristic(BLEChatProfile.CHARACTERISTIC_VERSION_UUID)); 261 | gatt.readCharacteristic(service.getCharacteristic(BLEChatProfile.CHARACTERISTIC_DESC_UUID)); 262 | gatt.setCharacteristicNotification(service.getCharacteristic(BLEChatProfile.CHARACTERISTIC_MESSAGE_UUID), true); 263 | gatt.setCharacteristicNotification(service.getCharacteristic(BLEChatProfile.CHARACTERISTIC_RFCOMM_TRANSFER_UUID), true); 264 | gatt.setCharacteristicNotification(service.getCharacteristic(BLEChatProfile.CHARACTERISTIC_BLE_TRANSFER_UUID), true); 265 | } 266 | } 267 | mHandler.post(new Runnable() { 268 | @Override 269 | public void run() { 270 | mBleChatEvents.onConnect(); 271 | } 272 | }); 273 | } 274 | 275 | @Override 276 | public void onCharacteristicRead(BluetoothGatt gatt, 277 | final BluetoothGattCharacteristic characteristic, 278 | int status) { 279 | super.onCharacteristicRead(gatt, characteristic, status); 280 | if (BLEChatProfile.CHARACTERISTIC_MESSAGE_UUID.equals(characteristic.getUuid())) { 281 | final String msg = characteristic.getStringValue(0); 282 | mHandler.post(new Runnable() { 283 | @Override 284 | public void run() { 285 | mBleChatEvents.onMessage(msg); 286 | } 287 | }); 288 | 289 | //Register for further updates as notifications 290 | gatt.setCharacteristicNotification(characteristic, true); 291 | } 292 | if (BLEChatProfile.CHARACTERISTIC_VERSION_UUID.equals(characteristic.getUuid())) { 293 | final String version = characteristic.getStringValue(0); 294 | mHandler.post(new Runnable() { 295 | @Override 296 | public void run() { 297 | mBleChatEvents.onVersion(version); 298 | } 299 | }); 300 | 301 | //Register for further updates as notifications 302 | gatt.setCharacteristicNotification(characteristic, true); 303 | } 304 | if (BLEChatProfile.CHARACTERISTIC_DESC_UUID.equals(characteristic.getUuid())) { 305 | final String description = characteristic.getStringValue(0); 306 | mHandler.post(new Runnable() { 307 | @Override 308 | public void run() { 309 | mBleChatEvents.onDescription(description); 310 | } 311 | }); 312 | 313 | //Register for further updates as notifications 314 | gatt.setCharacteristicNotification(characteristic, true); 315 | } 316 | } 317 | 318 | @Override 319 | public void onCharacteristicWrite (BluetoothGatt gatt, 320 | BluetoothGattCharacteristic characteristic, 321 | int status){ 322 | if (BLEChatProfile.CHARACTERISTIC_BLE_TRANSFER_UUID.equals(characteristic.getUuid())){ 323 | final int chatStatus = (status == BluetoothGatt.GATT_SUCCESS ? BLEChatEvents.SENT_SUCCEED : BLEChatEvents.SENT_FAILED); 324 | mHandler.post(new Runnable() { 325 | @Override 326 | public void run() { 327 | mBleChatEvents.onStreamSent(chatStatus); 328 | } 329 | }); 330 | } 331 | 332 | } 333 | 334 | @Override 335 | public void onMtuChanged (BluetoothGatt gatt, 336 | int mtu, 337 | int status){ 338 | final int chatStatus = (status == BluetoothGatt.GATT_SUCCESS ? BLECentralChatEvents.MTU_CHANGE_SUCCEED : BLECentralChatEvents.MTU_CHANGE_FAILED); 339 | mMtu = mtu; 340 | mHandler.post(new Runnable() { 341 | @Override 342 | public void run() { 343 | mBleChatEvents.onMtuChanged(chatStatus, mMtu); 344 | } 345 | }); 346 | } 347 | 348 | 349 | @Override 350 | public void onCharacteristicChanged(BluetoothGatt gatt, 351 | final BluetoothGattCharacteristic characteristic) { 352 | super.onCharacteristicChanged(gatt, characteristic); 353 | Log.i(TAG, "Notification of message characteristic changed on server."); 354 | if (BLEChatProfile.CHARACTERISTIC_MESSAGE_UUID.equals(characteristic.getUuid())) { 355 | mHandler.post(new Runnable() { 356 | @Override 357 | public void run() { 358 | mBleChatEvents.onMessage(characteristic.getStringValue(0)); 359 | } 360 | }); 361 | } else if (BLEChatProfile.CHARACTERISTIC_RFCOMM_TRANSFER_UUID.equals(characteristic.getUuid())) { 362 | mHandler.post(new Runnable() { 363 | @Override 364 | public void run() { 365 | mRfcommSocketAddress = characteristic.getStringValue(0); 366 | connect2RfcommSocket(); 367 | //mBleChatEvents.onTransfer(characteristic.getStringValue(0)); 368 | } 369 | }); 370 | } else if (BLEChatProfile.CHARACTERISTIC_BLE_TRANSFER_UUID.equals(characteristic.getUuid())) { 371 | mHandler.post(new Runnable() { 372 | @Override 373 | public void run() { 374 | mBleChatEvents.onInfo("BLE_TRANS Charac changed!!"); 375 | } 376 | }); 377 | } 378 | } 379 | }; //End BluetoothGattCallback 380 | 381 | public void send(byte[] data) { 382 | final BluetoothGattCharacteristic characteristic = mConnectedGatt 383 | .getService(BLEChatProfile.SERVICE_UUID) 384 | .getCharacteristic(BLEChatProfile.CHARACTERISTIC_MESSAGE_UUID); 385 | 386 | characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); 387 | characteristic.setValue(data); 388 | if(!mConnectedGatt.writeCharacteristic(characteristic)){ 389 | mBleChatEvents.onConnectionError("Couldn't send data!!"); 390 | } 391 | } 392 | 393 | public void send(String msg){ 394 | send(msg.getBytes()); 395 | } 396 | 397 | /** 398 | * 399 | */ 400 | public void sendFile(final Uri uri){ 401 | mHandler.post(new Runnable() { 402 | @Override 403 | public void run() { 404 | try{ 405 | InputStream is = mContext.getContentResolver().openInputStream(uri); 406 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 407 | byte[] b = new byte[1024]; 408 | int bytesRead = 0; 409 | while ((bytesRead = is.read(b)) != -1) { 410 | bos.write(b, 0, bytesRead); 411 | } 412 | send2Rfcomm(bos.toByteArray()); 413 | }catch(FileNotFoundException ex){ 414 | 415 | }catch(IOException ex){ 416 | 417 | } 418 | } 419 | }); 420 | } 421 | 422 | /** 423 | * 424 | * @param data 425 | */ 426 | private synchronized void send2Rfcomm(byte[] data){ 427 | try { 428 | OutputStream stream = mSocket.getOutputStream(); 429 | stream.write(data); 430 | }catch (IOException e){ 431 | mHandler.post(new Runnable() { 432 | @Override 433 | public void run() { 434 | mBleChatEvents.onConnectionError("Error sending message to RFCOMM Socket"); 435 | } 436 | }); 437 | 438 | } 439 | } 440 | 441 | 442 | /** 443 | * Sends a MTU size block of data 444 | */ 445 | public synchronized void sendData() { 446 | 447 | //byte[] data = getAlphabetDataBlock(mMtu); 448 | byte[] data = new byte[mMtu]; 449 | 450 | final BluetoothGattCharacteristic characteristic = mConnectedGatt 451 | .getService(BLEChatProfile.SERVICE_UUID) 452 | .getCharacteristic(BLEChatProfile.CHARACTERISTIC_BLE_TRANSFER_UUID); 453 | 454 | characteristic.setValue(data); 455 | characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); 456 | int iRetries = 0; 457 | while (!mConnectedGatt.writeCharacteristic(characteristic)) { 458 | try { 459 | if (iRetries > MAX_RETRIES) { 460 | mBleChatEvents.onConnectionError("Couldn't send more data!!"); 461 | return; 462 | } 463 | iRetries++; 464 | Log.d(TAG, "Error sending data. Retrying... " + iRetries); 465 | // We are in StreamThread thread.... so we can sleep 466 | Thread.sleep(BLEChatProfile.SEND_INTERVAL); 467 | } catch (InterruptedException ex) { 468 | mBleChatEvents.onConnectionError("Interrupted while sleeping!!"); 469 | return; 470 | } 471 | } 472 | } 473 | 474 | 475 | /** 476 | * Gets a block of numElems size of the alphabet. Subsequent calls to this method 477 | * will start the new block with the next letter of the alphabet. 478 | */ 479 | private int mLetterCounter = 97; 480 | private byte[] getAlphabetDataBlock(int numElems){ 481 | String string = ""; 482 | 483 | for(int e = 0; e < numElems - 3; e++){ 484 | string += String.valueOf((char)mLetterCounter); 485 | mLetterCounter = (mLetterCounter > 121 ? 97 : mLetterCounter + 1); 486 | } 487 | byte [] data = string.getBytes(); 488 | byte [] finalData = new byte[data.length + 3]; 489 | byte [] header = {0,0,0}; 490 | 491 | 492 | System.arraycopy(data, 0, finalData, 0, data.length); 493 | System.arraycopy(header,0, finalData, finalData.length - 3, header.length ); 494 | return finalData; 495 | } 496 | 497 | 498 | /** 499 | * Default BLE MTU is 20 500 | */ 501 | private int mMtu = 20; 502 | 503 | /** 504 | * Changes MTU. 505 | * This will trigger onMtuChanged() callback 506 | * @param size 507 | */ 508 | public void changeMtu(int size){ 509 | if (!mConnectedGatt.requestMtu(size)) { 510 | Log.d(TAG,"Couldn't set MTU!!"); 511 | mHandler.post(new Runnable() { 512 | @Override 513 | public void run() { 514 | mBleChatEvents.onConnectionError("Couldn't set MTU!!"); 515 | } 516 | }); 517 | return; 518 | } 519 | Log.d(TAG, "MTU set to " + size); 520 | } 521 | 522 | 523 | /** 524 | * Sets the final MTU 525 | */ 526 | public void setMtu(int size){ 527 | mMtu = size; 528 | }; 529 | 530 | /** 531 | * Gets the final MTU 532 | */ 533 | public int getMtu(){ 534 | return mMtu; 535 | } 536 | 537 | 538 | } 539 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEChatEvents.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | /** 4 | * Created by jgomez on 4/05/16. 5 | */ 6 | public interface BLEChatEvents { 7 | int SENT_SUCCEED = 0; 8 | int SENT_FAILED = 1; 9 | 10 | void onMessage(String msg); 11 | void onData(byte[] data); 12 | void onDataStream(byte[] data); 13 | void onStreamSent(int status); 14 | void onInfo(String msg); 15 | void onConnectionError(String error); 16 | } 17 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEChatProfile.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | import android.bluetooth.BluetoothGatt; 4 | import android.bluetooth.BluetoothProfile; 5 | 6 | import java.util.UUID; 7 | 8 | /** 9 | * Created by jgomez on 26/04/16. 10 | */ 11 | public class BLEChatProfile { 12 | public static UUID SERVICE_UUID = UUID.fromString("1706BBC0-88AB-4B8D-877E-2237916EE929"); 13 | public static UUID CHARACTERISTIC_MESSAGE_UUID = UUID.fromString("275348FB-C14D-4FD5-B434-7C3F351DEA5F"); 14 | public static UUID DESCRIPTOR_MESSAGE_UUID = UUID.fromString("45bda094-ff40-4cb8-835d-0da8742bb1eb"); 15 | public static UUID CHARACTERISTIC_VERSION_UUID = UUID.fromString("BD28E457-4026-4270-A99F-F9BC20182E15"); 16 | public static UUID CHARACTERISTIC_DESC_UUID = UUID.fromString("FDD00F2A-DAA3-47F5-8715-9DE659E5EB7B"); 17 | public static UUID CHARACTERISTIC_RFCOMM_TRANSFER_UUID = UUID.fromString("34df5318-94de-4c1d-af31-31616c7fd9dd"); 18 | public static UUID DESCRIPTOR_RFCOMM_TRANSFER_UUID = UUID.fromString("42a210d6-b6c5-4f82-a9cc-67d0e1d76a1e"); 19 | public static UUID CHARACTERISTIC_BLE_TRANSFER_UUID = UUID.fromString("482f1096-137b-46cc-8ca8-3457c15cc433"); 20 | public static UUID DESCRIPTOR_BLE_TRANSFER_UUID = UUID.fromString("421ecb34-bb49-4b70-a5ea-042c1f38ec32"); 21 | 22 | public static final int SEND_INTERVAL = 100; 23 | 24 | 25 | private static String mVersion = "1"; 26 | private static String mDescription = "BLEChat - Juan Gomez :_AtilA_"; 27 | 28 | /** 29 | * For Logging purposes only 30 | */ 31 | public static String getStateDescription(int state) { 32 | switch (state) { 33 | case BluetoothProfile.STATE_CONNECTED: 34 | return "Connected"; 35 | case BluetoothProfile.STATE_CONNECTING: 36 | return "Connecting"; 37 | case BluetoothProfile.STATE_DISCONNECTED: 38 | return "Disconnected"; 39 | case BluetoothProfile.STATE_DISCONNECTING: 40 | return "Disconnecting"; 41 | default: 42 | return "Unknown State "+state; 43 | } 44 | } 45 | 46 | public static String getStatusDescription(int status) { 47 | switch (status) { 48 | case BluetoothGatt.GATT_SUCCESS: 49 | return "SUCCESS"; 50 | default: 51 | return "Unknown Status "+status; 52 | } 53 | } 54 | 55 | public static String getVersion(){ 56 | return mVersion; 57 | } 58 | 59 | public static String getDescription(){ 60 | return mDescription; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEDiscoverCallback.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | import android.bluetooth.BluetoothDevice; 4 | 5 | /** 6 | * Created by jgomez on 27/04/16. 7 | */ 8 | public interface BLEDiscoverCallback { 9 | void onInitSuccess(); 10 | void onInitFailure(String message); 11 | void onScanResult(BluetoothDevice device, int rssi); 12 | void onScanFailed(String message); 13 | } 14 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEDiscoveringActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | import android.bluetooth.BluetoothAdapter; 4 | import android.bluetooth.BluetoothDevice; 5 | import android.content.BroadcastReceiver; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.content.IntentFilter; 9 | import android.os.Bundle; 10 | import android.app.Activity; 11 | import android.view.KeyEvent; 12 | import android.view.View; 13 | import android.webkit.WebView; 14 | import android.widget.AdapterView; 15 | import android.widget.ArrayAdapter; 16 | import android.widget.ListView; 17 | import android.widget.TextView; 18 | 19 | import com.example.android.bluetoothchat.R; 20 | 21 | import java.util.Comparator; 22 | 23 | public class BLEDiscoveringActivity extends Activity { 24 | 25 | private static final int BLE_DEVICE_NOT_FOUND = -1; 26 | public static String EXTRA_DEVICE_ADDRESS = "device_address"; 27 | public static String EXTRA_DEVICE_NAME = "device_name"; 28 | 29 | private class BLEDevice { 30 | public String mName; 31 | public String mAddress; 32 | public int mRssi; 33 | 34 | BLEDevice(String name, String address, int rssi){ 35 | mName = name; mAddress = address; mRssi = rssi; 36 | } 37 | @Override 38 | public String toString() { 39 | return mName + "@" + mAddress; 40 | } 41 | } 42 | 43 | ArrayAdapter mNewDevicesArrayAdapter; 44 | BLECentralHelper mBleChat = BLECentralHelper.getInstance(); 45 | 46 | 47 | @Override 48 | protected void onCreate(Bundle savedInstanceState) { 49 | super.onCreate(savedInstanceState); 50 | setContentView(R.layout.activity_ble_discovering); 51 | 52 | WebView animation = (WebView)findViewById(R.id.webView); 53 | animation.loadUrl("file:///android_asset/discovering_animation.html"); 54 | 55 | ListView newDevicesListView = (ListView) findViewById(R.id.bleDevicesFound); 56 | mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); 57 | newDevicesListView.setAdapter(mNewDevicesArrayAdapter); 58 | newDevicesListView.setOnItemClickListener(mDeviceClickListener); 59 | 60 | mBleChat.init(this, mBleDiscoverCallback); 61 | } 62 | 63 | private BLEDiscoverCallback mBleDiscoverCallback = new BLEDiscoverCallback() { 64 | @Override 65 | public void onInitSuccess() { 66 | mBleChat.startScan(); 67 | } 68 | 69 | @Override 70 | public void onInitFailure(String message) { 71 | /*TODO*/ finish(); 72 | } 73 | 74 | @Override 75 | public void onScanResult(BluetoothDevice device, int rssi) { 76 | BLEDevice bleDevice = new BLEDevice(device.getName(), device.getAddress(), rssi); 77 | for(int i=0; i < mNewDevicesArrayAdapter.getCount(); ++i){ 78 | if( mNewDevicesArrayAdapter.getItem(i).mAddress.compareTo(device.getAddress()) == 0 ){ 79 | return; 80 | } 81 | } 82 | 83 | mNewDevicesArrayAdapter.add(bleDevice); 84 | mNewDevicesArrayAdapter.sort(new Comparator() { 85 | @Override 86 | public int compare(BLEDevice first, BLEDevice second) { 87 | return first.mRssi > second.mRssi ? first.mRssi : second.mRssi; 88 | } 89 | }); 90 | } 91 | 92 | @Override 93 | public void onScanFailed(String message) { 94 | mBleChat.stopScan(); 95 | finish(); 96 | } 97 | }; 98 | 99 | @Override 100 | public boolean onKeyDown(int keyCode, KeyEvent event) 101 | { 102 | if ((keyCode == KeyEvent.KEYCODE_BACK)) 103 | { 104 | mBleChat.stopScan(); 105 | finish(); 106 | } 107 | return super.onKeyDown(keyCode, event); 108 | } 109 | 110 | private AdapterView.OnItemClickListener mDeviceClickListener 111 | = new AdapterView.OnItemClickListener() { 112 | public void onItemClick(AdapterView av, View v, int arg2, long arg3) { 113 | mBleChat.stopScan(); 114 | 115 | String name = ((TextView) v).getText().toString().split("@")[0]; 116 | // Get the device MAC address, which is the last 17 chars in the View 117 | String info = ((TextView) v).getText().toString(); 118 | String address = info.substring(info.length() - 17); 119 | 120 | // Create the result Intent and include the MAC address 121 | Intent intent = new Intent(); 122 | intent.putExtra(EXTRA_DEVICE_ADDRESS, address); 123 | intent.putExtra(EXTRA_DEVICE_NAME, name); 124 | // Set result and finish this Activity 125 | setResult(Activity.RESULT_OK, intent); 126 | finish(); 127 | } 128 | }; 129 | } 130 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEGattConstants.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | public class BLEGattConstants { 4 | public static final int GATT_UNDEFINED = -1; 5 | public static final int GATT_SERVICE_CREATION_SUCCESS = 0; 6 | public static final int GATT_SERVICE_CREATION_FAILED = 1; 7 | public static final int GATT_SERVICE_START_SUCCESS = 2; 8 | public static final int GATT_SERVICE_START_FAILED = 3; 9 | public static final int GATT_SERVICE_STOPPED = 4; 10 | public static final int SERVICE_UNAVAILABLE = 1; 11 | public static final int GATT_SERVICE_PRIMARY = 0; 12 | public static final int GATT_SERVICE_SECONDARY = 1; 13 | public static final int GATT_SERVER_PROFILE_INITIALIZED = 0; 14 | public static final int GATT_SERVER_PROFILE_UP = 1; 15 | public static final int GATT_SERVER_PROFILE_DOWN = 2; 16 | public static final int GATT_SUCCESS = 0; 17 | public static final int GATT_INVALID_HANDLE = 1; 18 | public static final int GATT_READ_NOT_PERMIT = 2; 19 | public static final int GATT_WRITE_NOT_PERMIT = 3; 20 | public static final int GATT_INVALID_PDU = 4; 21 | public static final int GATT_INSUF_AUTHENTICATION = 5; 22 | public static final int GATT_REQ_NOT_SUPPORTED = 6; 23 | public static final int GATT_INVALID_OFFSET = 7; 24 | public static final int GATT_INSUF_AUTHORIZATION = 8; 25 | public static final int GATT_PREPARE_Q_FULL = 9; 26 | public static final int GATT_NOT_FOUND = 10; 27 | public static final int GATT_NOT_LONG = 11; 28 | public static final int GATT_INSUF_KEY_SIZE = 12; 29 | public static final int GATT_INVALID_ATTR_LEN = 13; 30 | public static final int GATT_ERR_UNLIKELY = 14; 31 | public static final int GATT_INSUF_ENCRYPTION = 15; 32 | public static final int GATT_UNSUPPORT_GRP_TYPE = 16; 33 | public static final int GATT_INSUF_RESOURCE = 17; 34 | public static final int GATT_ILLEGAL_PARAMETER = 135; 35 | public static final int GATT_NO_RESOURCES = 128; 36 | public static final int GATT_INTERNAL_ERROR = 129; 37 | public static final int GATT_WRONG_STATE = 130; 38 | public static final int GATT_DB_FULL = 131; 39 | public static final int GATT_BUSY = 132; 40 | public static final int GATT_ERROR = 133; 41 | public static final int GATT_CMD_STARTED = 134; 42 | public static final int GATT_PENDING = 136; 43 | public static final int GATT_AUTH_FAIL = 137; 44 | public static final int GATT_MORE = 138; 45 | public static final int GATT_INVALID_CFG = 139; 46 | public static final byte GATT_AUTH_REQ_NONE = 0; 47 | public static final byte GATT_AUTH_REQ_NO_MITM = 1; 48 | public static final byte GATT_AUTH_REQ_MITM = 2; 49 | public static final byte GATT_AUTH_REQ_SIGNED_NO_MITM = 3; 50 | public static final byte GATT_AUTH_REQ_SIGNED_MITM = 4; 51 | public static final int GATT_PERM_READ = 1; 52 | public static final int GATT_PERM_READ_ENCRYPTED = 2; 53 | public static final int GATT_PERM_READ_ENC_MITM = 4; 54 | public static final int GATT_PERM_WRITE = 16; 55 | public static final int GATT_PERM_WRITE_ENCRYPTED = 32; 56 | public static final int GATT_PERM_WRITE_ENC_MITM = 64; 57 | public static final int GATT_PERM_WRITE_SIGNED = 128; 58 | public static final int GATT_PERM_WRITE_SIGNED_MITM = 256; 59 | public static final byte GATT_CHAR_PROP_BIT_BROADCAST = 1; 60 | public static final byte GATT_CHAR_PROP_BIT_READ = 2; 61 | public static final byte GATT_CHAR_PROP_BIT_WRITE_NR = 4; 62 | public static final byte GATT_CHAR_PROP_BIT_WRITE = 8; 63 | public static final byte GATT_CHAR_PROP_BIT_NOTIFY = 16; 64 | public static final byte GATT_CHAR_PROP_BIT_INDICATE = 32; 65 | public static final byte GATT_CHAR_PROP_BIT_AUTH = 64; 66 | public static final byte GATT_CHAR_PROP_BIT_EXT_PROP = -128; 67 | public static final byte SVC_INF_INVALID = -1; 68 | public static final int GATTC_TYPE_WRITE_NO_RSP = 1; 69 | public static final int GATTC_TYPE_WRITE = 2; 70 | public static final int GATT_FORMAT_RES = 0; 71 | public static final int GATT_FORMAT_BOOL = 1; 72 | public static final int GATT_FORMAT_2BITS = 2; 73 | public static final int GATT_FORMAT_NIBBLE = 3; 74 | public static final int GATT_FORMAT_UINT8 = 4; 75 | public static final int GATT_FORMAT_UINT12 = 5; 76 | public static final int GATT_FORMAT_UINT16 = 6; 77 | public static final int GATT_FORMAT_UINT24 = 7; 78 | public static final int GATT_FORMAT_UINT32 = 8; 79 | public static final int GATT_FORMAT_UINT48 = 9; 80 | public static final int GATT_FORMAT_UINT64 = 10; 81 | public static final int GATT_FORMAT_UINT128 = 11; 82 | public static final int GATT_FORMAT_SINT8 = 12; 83 | public static final int GATT_FORMAT_SINT12 = 13; 84 | public static final int GATT_FORMAT_SINT16 = 14; 85 | public static final int GATT_FORMAT_SINT24 = 15; 86 | public static final int GATT_FORMAT_SINT32 = 16; 87 | public static final int GATT_FORMAT_SINT48 = 17; 88 | public static final int GATT_FORMAT_SINT64 = 18; 89 | public static final int GATT_FORMAT_SINT128 = 19; 90 | public static final int GATT_FORMAT_FLOAT32 = 20; 91 | public static final int GATT_FORMAT_FLOAT64 = 21; 92 | public static final int GATT_FORMAT_SFLOAT = 22; 93 | public static final int GATT_FORMAT_FLOAT = 23; 94 | public static final int GATT_FORMAT_DUINT16 = 24; 95 | public static final int GATT_FORMAT_UTF8S = 25; 96 | public static final int GATT_FORMAT_UTF16S = 26; 97 | public static final int GATT_FORMAT_STRUCT = 27; 98 | public static final int GATT_FORMAT_MAX = 28; 99 | public static final int GATT_UUID_CHAR_EXT_PROP16 = 10496; 100 | public static final int GATT_UUID_CHAR_DESCRIPTION16 = 10497; 101 | public static final int GATT_UUID_CHAR_CLIENT_CONFIG16 = 10498; 102 | public static final int GATT_UUID_CHAR_SRVR_CONFIG16 = 10499; 103 | public static final int GATT_UUID_CHAR_PRESENT_FORMAT16 = 10500; 104 | public static final int GATT_UUID_CHAR_AGG_FORMAT16 = 10501; 105 | public static final int GATT_TRANSPORT_BREDR_LE = 2; 106 | public static final int GATT_TRANSPORT_BREDR = 1; 107 | public static final int GATT_TRANSPORT_LE = 0; 108 | public static final int GATT_UUID_TYPE_128 = 16; 109 | public static final int GATT_UUID_TYPE_32 = 4; 110 | public static final int GATT_UUID_TYPE_16 = 2; 111 | public static final int PREPARE_QUEUE_SIZE = 200; 112 | public static final int GATT_MAX_CHAR_VALUE_LENGTH = 100; 113 | public static final int GATT_CLIENT_CONFIG_NOTIFICATION_BIT = 1; 114 | public static final int GATT_CLIENT_CONFIG_INDICATION_BIT = 2; 115 | public static final int GATT_INVALID_CONN_ID = 65535; 116 | public static final int VALUE_DIRTY = 1; 117 | public static final int USER_DESCRIPTION_DIRTY = 2; 118 | public static final int EXT_PROP_DIRTY = 4; 119 | public static final int PRESENTATION_FORMAT_DIRTY = 8; 120 | public static final int CLIENT_CONFIG_DIRTY = 16; 121 | public static final int SERVER_CONFIG_DIRTY = 32; 122 | public static final int AGGREGATED_FORMAT_DIRTY = 64; 123 | public static final int USER_DESCRIPTOR_DIRTY = 128; 124 | public static final int ALL_DIRTY = 127; 125 | public static final byte GATT_ENCRYPT_NONE = 0; 126 | public static final byte GATT_ENCRYPT = 1; 127 | public static final byte GATT_ENCRYPT_NO_MITM = 2; 128 | public static final byte GATT_ENCRYPT_MITM = 3; 129 | } 130 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEMode.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | /** 4 | * Created by jgomez on 3/05/16. 5 | */ 6 | public enum BLEMode { 7 | PERIPHERAL, 8 | CENTRAL, 9 | NONE, /* Classic BT mode */ 10 | } 11 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEPeripheralChatEvents.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | import android.bluetooth.BluetoothDevice; 4 | 5 | /** 6 | * Created by jgomez on 4/05/16. 7 | */ 8 | public interface BLEPeripheralChatEvents extends BLEChatEvents { 9 | void onClientDisconnect(BluetoothDevice device); 10 | void onInitRfcommSocket(); 11 | void onConnectRfcommSocket(); 12 | } 13 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/ble/BLEPeripheralHelper.java: -------------------------------------------------------------------------------- 1 | package com.example.android.ble; 2 | 3 | import android.bluetooth.BluetoothAdapter; 4 | import android.bluetooth.BluetoothDevice; 5 | import android.bluetooth.BluetoothGatt; 6 | import android.bluetooth.BluetoothGattCharacteristic; 7 | import android.bluetooth.BluetoothGattDescriptor; 8 | import android.bluetooth.BluetoothGattServer; 9 | import android.bluetooth.BluetoothGattServerCallback; 10 | import android.bluetooth.BluetoothGattService; 11 | import android.bluetooth.BluetoothManager; 12 | import android.bluetooth.BluetoothServerSocket; 13 | import android.bluetooth.BluetoothSocket; 14 | import android.bluetooth.le.AdvertiseCallback; 15 | import android.bluetooth.le.AdvertiseData; 16 | import android.bluetooth.le.AdvertiseSettings; 17 | import android.bluetooth.le.BluetoothLeAdvertiser; 18 | import android.content.Context; 19 | import android.content.pm.PackageManager; 20 | import android.os.Handler; 21 | import android.os.ParcelUuid; 22 | import android.util.Log; 23 | 24 | import java.io.IOException; 25 | import java.io.InputStream; 26 | import java.io.UnsupportedEncodingException; 27 | import java.util.ArrayList; 28 | import java.util.Random; 29 | import java.util.UUID; 30 | 31 | /** 32 | * This singleton helper class will manage all the Bluetooth LE Peripheral stuff 33 | * A Peripheral BLE device is basically a device which can advertise services so other 34 | * Central devices can connect to it, so yes, is like a server. 35 | * 36 | * It communicates with other classes via Interfaces/Events like 37 | * * BLEPeripheralChatEvents 38 | * * BLEAdvertiseCallback 39 | * 40 | * Use un/register( objectImplementingInterface ) to start receiving events 41 | * 42 | */ 43 | public class BLEPeripheralHelper { 44 | 45 | private static final String TAG = "BLEPeripheralHelper"; 46 | 47 | private BluetoothManager mBluetoothManager; 48 | private BluetoothAdapter mBluetoothAdapter; 49 | private BluetoothLeAdvertiser mBluetoothLeAdvertiser; 50 | private BluetoothGattServer mGattServer; 51 | private Context mContext; 52 | //private BLEAdvertiseCallback mBleAdvCallback; 53 | private ArrayList mAdvListeners = new ArrayList<>(); 54 | private ArrayList mChatListeners = new ArrayList<>(); 55 | 56 | private ArrayList mConnectedDevices; 57 | private Object mLock = new Object(); 58 | private Handler mHandler = new Handler(); 59 | 60 | private AcceptThread mInsecureAcceptThread; 61 | 62 | 63 | private static BLEPeripheralHelper instance = new BLEPeripheralHelper(); 64 | 65 | private BLEPeripheralHelper() { 66 | } 67 | 68 | public static BLEPeripheralHelper getInstance() { 69 | if (instance == null) { 70 | synchronized (BLEPeripheralHelper.class) { 71 | if (instance == null) { 72 | instance = new BLEPeripheralHelper(); 73 | } 74 | } 75 | } 76 | return instance; 77 | } 78 | 79 | /** 80 | * Register listeners for the Advertisement phase. The listeners will receive all events 81 | * fired in this phase. 82 | * @param advListener 83 | */ 84 | public void register(BLEAdvertiseCallback advListener) { 85 | mAdvListeners.add(advListener); 86 | } 87 | 88 | /** 89 | * Register listeners for the Chatting phase. The listeners will receive all events 90 | * fired in this phase. 91 | * @param chatEventListener 92 | */ 93 | public void register(BLEPeripheralChatEvents chatEventListener) { 94 | mChatListeners.add(chatEventListener); 95 | } 96 | 97 | /** 98 | * Unregister listeners of the advertisement phase 99 | * @param advListener 100 | */ 101 | public void unregister(BLEAdvertiseCallback advListener) { 102 | mAdvListeners.remove(advListener); 103 | } 104 | 105 | 106 | /** 107 | * Unregister listeners of the chatting phase 108 | * @param chatEventListener 109 | */ 110 | public void unregister(BLEPeripheralChatEvents chatEventListener) { 111 | mChatListeners.remove(chatEventListener); 112 | } 113 | 114 | /** 115 | * Events for the advertising phase 116 | */ 117 | private enum NotifyAdvAction { 118 | NOTIFY_ADV_ACTION_INIT_FAILURE, 119 | NOTIFY_ADV_ACTION_INIT_SUCCESS, 120 | NOTIFY_ADV_ACTION_CLIENT_CONNECT, 121 | NOTIFY_ADV_ACTION_INFO, 122 | NOTIFY_ADV_ACTION_CONNECTION_ERROR, 123 | } 124 | 125 | ; 126 | 127 | /** 128 | * Events for the chatting phase 129 | */ 130 | private enum NotifyChatAction { 131 | NOTIFY_CHAT_ACTION_MESSAGE, 132 | NOTIFY_CHAT_ACTION_INFO, 133 | NOTIFY_CHAT_ACTION_CLIENT_DISCONNECT, 134 | NOTIFY_CHAT_ACTION_CONNECTION_ERROR, 135 | NOTIFY_CHAT_ACTION_INIT_RFCOMM_SOCKET, 136 | NOTIFY_CHAT_ACTION_CONNECT_RFCOMM_SOCKET, 137 | NOTIFY_CHAT_ACTION_DATA_RFCOMM_SOCKET, 138 | NOTIFY_CHAT_ACTION_BLE_STREAM, 139 | } 140 | 141 | 142 | /** 143 | * Notifies via events to all registered listeners in the Advertising phase. 144 | * 145 | * @param action 146 | * @param data 147 | */ 148 | private void notifyAdvListeners(NotifyAdvAction action, Object data) { 149 | for (BLEAdvertiseCallback listener : mAdvListeners) { 150 | switch (action) { 151 | case NOTIFY_ADV_ACTION_INIT_SUCCESS: 152 | listener.onInitSuccess(); 153 | break; 154 | case NOTIFY_ADV_ACTION_INIT_FAILURE: 155 | listener.onInitFailure((String) data); 156 | break; 157 | case NOTIFY_ADV_ACTION_CLIENT_CONNECT: 158 | listener.onClientConnect((BluetoothDevice) data); 159 | break; 160 | case NOTIFY_ADV_ACTION_INFO: 161 | listener.onInfo((String) data); 162 | break; 163 | case NOTIFY_ADV_ACTION_CONNECTION_ERROR: 164 | listener.onError((String) data); 165 | break; 166 | } 167 | } 168 | } 169 | 170 | 171 | /** 172 | * Notifies via events to all registered listeners in the Chatting phase 173 | * 174 | * @param action 175 | * @param data 176 | */ 177 | 178 | private void notifyChatListeners(NotifyChatAction action, Object data) { 179 | for (BLEPeripheralChatEvents listener : mChatListeners) { 180 | switch (action) { 181 | case NOTIFY_CHAT_ACTION_MESSAGE: 182 | listener.onMessage((String) data); 183 | break; 184 | case NOTIFY_CHAT_ACTION_INFO: 185 | listener.onInfo((String) data); 186 | break; 187 | case NOTIFY_CHAT_ACTION_CLIENT_DISCONNECT: 188 | listener.onClientDisconnect((BluetoothDevice) data); 189 | break; 190 | case NOTIFY_CHAT_ACTION_CONNECTION_ERROR: 191 | listener.onConnectionError((String) data); 192 | break; 193 | case NOTIFY_CHAT_ACTION_INIT_RFCOMM_SOCKET: 194 | listener.onInitRfcommSocket(); 195 | break; 196 | case NOTIFY_CHAT_ACTION_CONNECT_RFCOMM_SOCKET: 197 | listener.onConnectRfcommSocket(); 198 | break; 199 | case NOTIFY_CHAT_ACTION_DATA_RFCOMM_SOCKET: 200 | listener.onData((byte [])data); 201 | break; 202 | case NOTIFY_CHAT_ACTION_BLE_STREAM: 203 | listener.onDataStream((byte [])data); 204 | } 205 | } 206 | } 207 | 208 | 209 | public void init(Context context) { 210 | if (context == null) { 211 | notifyAdvListeners(NotifyAdvAction.NOTIFY_ADV_ACTION_INIT_FAILURE, "Context cannot be null!!"); 212 | return; 213 | } 214 | mContext = context; 215 | mConnectedDevices = new ArrayList(); 216 | mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE); 217 | mBluetoothAdapter = mBluetoothManager.getAdapter(); 218 | if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { 219 | //mBleAdvCallback.onInitFailure("Bluetooth not supported in this device!!"); 220 | notifyAdvListeners(NotifyAdvAction.NOTIFY_ADV_ACTION_INIT_FAILURE, "Bluetooth not supported in this device!!"); 221 | return; 222 | } 223 | 224 | if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { 225 | //mBleAdvCallback.onInitFailure("Bluetooth LE is not supported in this devices!!"); 226 | notifyAdvListeners(NotifyAdvAction.NOTIFY_ADV_ACTION_INIT_FAILURE, "Bluetooth LE is not supported in this devices!!"); 227 | return; 228 | } 229 | //mBleAdvCallback.onInitSuccess(); 230 | notifyAdvListeners(NotifyAdvAction.NOTIFY_ADV_ACTION_INIT_SUCCESS, null); 231 | } 232 | 233 | private BluetoothGattServerCallback mGattServerCallback = new BluetoothGattServerCallback() { 234 | @Override 235 | public void onConnectionStateChange(BluetoothDevice device, int status, int newState) { 236 | super.onConnectionStateChange(device, status, newState); 237 | Log.i(TAG, "onConnectionStateChange " 238 | + BLEChatProfile.getStatusDescription(status) + " " 239 | + BLEChatProfile.getStateDescription(newState)); 240 | if (status == BluetoothGatt.GATT_SUCCESS) { 241 | if (newState == BluetoothGatt.STATE_CONNECTED) { 242 | mConnectedDevices.add(device); 243 | notifyAdvListeners(NotifyAdvAction.NOTIFY_ADV_ACTION_CLIENT_CONNECT, device); 244 | } else if (newState == BluetoothGatt.STATE_DISCONNECTED) { 245 | mConnectedDevices.remove(device); 246 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_CLIENT_DISCONNECT, device); 247 | } 248 | } else { 249 | String error = "Error:" + status; 250 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_CONNECTION_ERROR, error); 251 | notifyAdvListeners(NotifyAdvAction.NOTIFY_ADV_ACTION_CONNECTION_ERROR, error); 252 | } 253 | } 254 | 255 | @Override 256 | public void onCharacteristicReadRequest(BluetoothDevice device, 257 | int requestId, 258 | int offset, 259 | BluetoothGattCharacteristic characteristic) { 260 | super.onCharacteristicReadRequest(device, requestId, offset, characteristic); 261 | Log.i(TAG, "onCharacteristicReadRequest " + characteristic.getUuid().toString()); 262 | byte [] value; 263 | if (BLEChatProfile.CHARACTERISTIC_VERSION_UUID.equals(characteristic.getUuid())) { 264 | value = getCharacteristicVersionValue(); 265 | } else if (BLEChatProfile.CHARACTERISTIC_DESC_UUID.equals(characteristic.getUuid())) { 266 | value = getCharacteristicDescValue(); 267 | } else { 268 | value = new byte[0]; 269 | } 270 | 271 | mGattServer.sendResponse(device, 272 | requestId, 273 | BluetoothGatt.GATT_SUCCESS, 274 | offset, 275 | value); 276 | } 277 | 278 | @Override 279 | public void onCharacteristicWriteRequest(BluetoothDevice device, 280 | int requestId, 281 | BluetoothGattCharacteristic characteristic, 282 | boolean preparedWrite, 283 | boolean responseNeeded, 284 | int offset, 285 | byte[] value) { 286 | super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value); 287 | Log.i(TAG, "onCharacteristicWriteRequest " + characteristic.getUuid().toString()); 288 | int gatResult = BluetoothGatt.GATT_SUCCESS; 289 | try{ 290 | if (BLEChatProfile.CHARACTERISTIC_MESSAGE_UUID.equals(characteristic.getUuid())) { 291 | String msg = new String(value, "UTF-8"); 292 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_MESSAGE, msg); 293 | /*for (BluetoothDevice connectedDevice : mConnectedDevices) { 294 | BluetoothGattCharacteristic msgCharacteristic = mGattServer.getService(BLEChatProfile.SERVICE_UUID) 295 | .getCharacteristic(BLEChatProfile.CHARACTERISTIC_DESC_UUID); 296 | msgCharacteristic.setValue(msg.getBytes()); 297 | mGattServer.notifyCharacteristicChanged(connectedDevice, msgCharacteristic, false); 298 | }*/ 299 | }else if(BLEChatProfile.CHARACTERISTIC_BLE_TRANSFER_UUID.equals(characteristic.getUuid())) { 300 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_BLE_STREAM, value); 301 | } 302 | }catch (UnsupportedEncodingException ex) { 303 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_CONNECTION_ERROR, ex.toString()); 304 | gatResult = BluetoothGatt.GATT_FAILURE; 305 | }finally{ 306 | if (responseNeeded) { 307 | mGattServer.sendResponse(device, 308 | requestId, 309 | gatResult, 310 | offset, 311 | value); 312 | } 313 | } 314 | } 315 | 316 | @Override 317 | public void onDescriptorWriteRequest(BluetoothDevice device, 318 | int requestId, BluetoothGattDescriptor descriptor, 319 | boolean preparedWrite, boolean responseNeeded, 320 | int offset, byte[] value) { 321 | if (responseNeeded) { 322 | mGattServer.sendResponse(device, 323 | requestId, 324 | BluetoothGatt.GATT_SUCCESS, 325 | offset, 326 | value); 327 | } 328 | } 329 | }; 330 | 331 | /** 332 | * Initializes all BLE Peripheral services so we can advertise later on. 333 | */ 334 | private void initService() { 335 | mGattServer = mBluetoothManager.openGattServer(mContext, mGattServerCallback); 336 | 337 | BluetoothGattService service = new BluetoothGattService(BLEChatProfile.SERVICE_UUID, 338 | BluetoothGattService.SERVICE_TYPE_PRIMARY); 339 | 340 | BluetoothGattCharacteristic messageCharacteristic = 341 | new BluetoothGattCharacteristic(BLEChatProfile.CHARACTERISTIC_MESSAGE_UUID, 342 | //Read-write characteristic, supports notifications 343 | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_NOTIFY, 344 | BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE); 345 | BluetoothGattDescriptor messageDesc = new BluetoothGattDescriptor(BLEChatProfile.DESCRIPTOR_MESSAGE_UUID, 346 | BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ); 347 | messageCharacteristic.addDescriptor(messageDesc); 348 | 349 | BluetoothGattCharacteristic versionCharacteristic = 350 | new BluetoothGattCharacteristic(BLEChatProfile.CHARACTERISTIC_VERSION_UUID, 351 | //Read-only characteristic 352 | BluetoothGattCharacteristic.PROPERTY_READ, 353 | BluetoothGattCharacteristic.PERMISSION_READ); 354 | 355 | BluetoothGattCharacteristic descriptionCharacteristic = 356 | new BluetoothGattCharacteristic(BLEChatProfile.CHARACTERISTIC_DESC_UUID, 357 | //Read-write characteristic, supports notifications 358 | BluetoothGattCharacteristic.PROPERTY_READ, 359 | BluetoothGattCharacteristic.PERMISSION_READ); 360 | 361 | BluetoothGattCharacteristic transferCharacteristic = 362 | new BluetoothGattCharacteristic(BLEChatProfile.CHARACTERISTIC_RFCOMM_TRANSFER_UUID, 363 | //Read-write characteristic, supports notifications 364 | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_NOTIFY, 365 | BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE); 366 | BluetoothGattDescriptor transferRateDesc = new BluetoothGattDescriptor(BLEChatProfile.DESCRIPTOR_RFCOMM_TRANSFER_UUID, 367 | BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ); 368 | transferCharacteristic.addDescriptor(transferRateDesc); 369 | 370 | BluetoothGattCharacteristic transferBleCharacteristic = 371 | new BluetoothGattCharacteristic(BLEChatProfile.CHARACTERISTIC_BLE_TRANSFER_UUID, 372 | //Read-write characteristic, supports notifications 373 | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE | BluetoothGattCharacteristic.PROPERTY_NOTIFY, 374 | BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE); 375 | BluetoothGattDescriptor transferBleDesc = new BluetoothGattDescriptor(BLEChatProfile.DESCRIPTOR_BLE_TRANSFER_UUID, 376 | BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ); 377 | transferBleCharacteristic.addDescriptor(transferBleDesc); 378 | 379 | 380 | service.addCharacteristic(descriptionCharacteristic); 381 | service.addCharacteristic(versionCharacteristic); 382 | service.addCharacteristic(messageCharacteristic); 383 | service.addCharacteristic(transferCharacteristic); 384 | service.addCharacteristic(transferBleCharacteristic); 385 | 386 | 387 | mGattServer.addService(service); 388 | } 389 | 390 | /** 391 | * Initialize RFCOMM Socket thread for Classic Bluetooth communications/transfers 392 | */ 393 | public void initRfcommService() { 394 | if (mInsecureAcceptThread == null) { 395 | mInsecureAcceptThread = new AcceptThread(false); 396 | mInsecureAcceptThread.start(); 397 | } 398 | sendTransferReady(); 399 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_INIT_RFCOMM_SOCKET, null); 400 | } 401 | 402 | /** 403 | * Stops the RFCOMM Socket 404 | */ 405 | public void stopRfcommService(){ 406 | if (mInsecureAcceptThread != null) { 407 | mInsecureAcceptThread.end(); 408 | } 409 | mInsecureAcceptThread = null; 410 | } 411 | 412 | /** 413 | * Advertise the services initialized before on initService() method 414 | */ 415 | private void advertiseService() { 416 | AdvertiseSettings settings = new AdvertiseSettings.Builder() 417 | .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED) 418 | .setConnectable(true) 419 | .setTimeout(0) 420 | .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM) 421 | .build(); 422 | 423 | AdvertiseData data = new AdvertiseData.Builder() 424 | .setIncludeDeviceName(true) 425 | .addServiceUuid(new ParcelUuid(BLEChatProfile.SERVICE_UUID)) 426 | .build(); 427 | 428 | /*int MANUFACTURER_ID = 0x45; 429 | byte [] manufacturerData = { 430 | 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 431 | 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 432 | //0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 433 | //0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 434 | //0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79 435 | }; 436 | 437 | AdvertiseData data = new AdvertiseData.Builder() 438 | .addManufacturerData(MANUFACTURER_ID, manufacturerData) 439 | .build();*/ 440 | 441 | mBluetoothLeAdvertiser.startAdvertising(settings, data, mAdvertiseCallback); 442 | } 443 | 444 | /** 445 | * Initialize BLE Advertisement 446 | */ 447 | public void startAdvertising() { 448 | 449 | if (!mBluetoothAdapter.isMultipleAdvertisementSupported()) { 450 | postStatusMessage("Bluetooth LE Peripheral mode is not supported in this device!!"); 451 | return; 452 | } 453 | 454 | if (mBluetoothLeAdvertiser == null) { 455 | mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser(); 456 | if (mBluetoothLeAdvertiser == null) { 457 | postStatusMessage("Error initializing BLE Advertiser"); 458 | return; 459 | } 460 | } 461 | 462 | initService(); 463 | advertiseService(); 464 | } 465 | 466 | /* 467 | * Terminate the advertiser 468 | */ 469 | public void stopAdvertising() { 470 | if (mBluetoothLeAdvertiser == null) 471 | return; 472 | 473 | mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback); 474 | } 475 | 476 | 477 | private AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() { 478 | @Override 479 | public void onStartSuccess(AdvertiseSettings settingsInEffect) { 480 | Log.i(TAG, "Peripheral Advertise Started."); 481 | postStatusMessage("GATT Server Ready"); 482 | } 483 | 484 | @Override 485 | public void onStartFailure(int errorCode) { 486 | Log.w(TAG, "Peripheral Advertise Failed: " + errorCode); 487 | postStatusMessage("GATT Server Error " + errorCode); 488 | } 489 | }; 490 | 491 | /** 492 | * Helper function to set the Status message 493 | */ 494 | private void postStatusMessage(final String message) { 495 | mHandler.post(new Runnable() { 496 | @Override 497 | public void run() { 498 | notifyAdvListeners(NotifyAdvAction.NOTIFY_ADV_ACTION_INFO, message); 499 | } 500 | }); 501 | } 502 | 503 | /** 504 | * Returns an array of bytes representing the value of the Version characteristic 505 | * @return 506 | */ 507 | private byte[] getCharacteristicVersionValue() { 508 | synchronized (mLock) { 509 | return BLEChatProfile.getVersion().getBytes(); 510 | } 511 | } 512 | 513 | /** 514 | * Returns an array of bytes representing the value of the Description characteristic 515 | * @return 516 | */ 517 | private byte[] getCharacteristicDescValue() { 518 | synchronized (mLock) { 519 | return BLEChatProfile.getDescription().getBytes(); 520 | } 521 | } 522 | 523 | public void send(String msg) { 524 | for (BluetoothDevice device : mConnectedDevices) { 525 | BluetoothGattCharacteristic msgCharacteristic = mGattServer.getService(BLEChatProfile.SERVICE_UUID) 526 | .getCharacteristic(BLEChatProfile.CHARACTERISTIC_MESSAGE_UUID); 527 | msgCharacteristic.setValue(msg); 528 | mGattServer.notifyCharacteristicChanged(device, msgCharacteristic, false); 529 | } 530 | } 531 | 532 | /** 533 | * Sends a block of random data 534 | */ 535 | public synchronized void sendStream(){ 536 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_INFO, "Not tested yet!"); 537 | byte[] randomBytes = new byte[512]; 538 | (new Random()).nextBytes(randomBytes); 539 | 540 | for (BluetoothDevice device : mConnectedDevices) { 541 | BluetoothGattCharacteristic transferCharacteristic = mGattServer.getService(BLEChatProfile.SERVICE_UUID) 542 | .getCharacteristic(BLEChatProfile.CHARACTERISTIC_BLE_TRANSFER_UUID); 543 | transferCharacteristic.setValue(randomBytes); 544 | mGattServer.notifyCharacteristicChanged(device, transferCharacteristic, false); 545 | } 546 | } 547 | 548 | 549 | /** 550 | * This will send back a message with the Bluetooth interface address to the Central device who wanted to 551 | * initialize the RFCOMM transfer. The Central device will use this address in the scanning phase to uniquely 552 | * identify this devices so he can filter and connect to it. 553 | */ 554 | private void sendTransferReady(){ 555 | for (BluetoothDevice device : mConnectedDevices) { 556 | BluetoothGattCharacteristic transferCharacteristic = mGattServer.getService(BLEChatProfile.SERVICE_UUID) 557 | .getCharacteristic(BLEChatProfile.CHARACTERISTIC_RFCOMM_TRANSFER_UUID); 558 | String macAddress = android.provider.Settings.Secure.getString(mContext.getContentResolver(), "bluetooth_address"); 559 | transferCharacteristic.setValue(macAddress); 560 | mGattServer.notifyCharacteristicChanged(device, transferCharacteristic, false); 561 | } 562 | } 563 | 564 | 565 | // Name for the SDP record when creating server socket 566 | private static final String NAME_SECURE = "BluetoothLEChatSecure"; 567 | private static final String NAME_INSECURE = "BluetoothLEChatInsecure"; 568 | // Unique UUID for this application 569 | private static final UUID MY_UUID_SECURE = 570 | UUID.fromString("caa8f277-6b87-49fb-a11b-ab9c9dacbd44"); 571 | private static final UUID MY_UUID_INSECURE = 572 | UUID.fromString("83769a57-e930-4496-8ece-fec16420c77c"); 573 | 574 | private class AcceptThread extends Thread { 575 | // The local server socket 576 | private final BluetoothServerSocket mmServerSocket; 577 | private String mSocketType; 578 | boolean mEnd = false; 579 | 580 | public AcceptThread(boolean secure) { 581 | BluetoothServerSocket tmp = null; 582 | mSocketType = secure ? "Secure" : "Insecure"; 583 | 584 | // Create a new listening server socket 585 | try { 586 | if (secure) { 587 | tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, 588 | MY_UUID_SECURE); 589 | } else { 590 | tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord( 591 | NAME_INSECURE, MY_UUID_INSECURE); 592 | } 593 | } catch (IOException e) { 594 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_CONNECTION_ERROR, "Socket Type: " + mSocketType + "listen() failed"); 595 | } 596 | mmServerSocket = tmp; 597 | } 598 | 599 | public void run() { 600 | com.example.android.common.logger.Log.d(TAG, "Socket Type: " + mSocketType + 601 | "BEGIN mAcceptThread" + this); 602 | setName("AcceptThread" + mSocketType); 603 | 604 | BluetoothSocket socket = null; 605 | try { 606 | // This is a blocking call and will only return on a 607 | // successful connection or an exception 608 | socket = mmServerSocket.accept(); 609 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_CONNECT_RFCOMM_SOCKET, null); 610 | int bytesRead = 0; 611 | do 612 | { 613 | InputStream is = socket.getInputStream(); 614 | byte[] buffer = new byte[1024]; 615 | bytesRead = is.read(buffer); 616 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_DATA_RFCOMM_SOCKET, buffer); 617 | }while(bytesRead != 0 && !mEnd); 618 | 619 | } catch (IOException e) { 620 | notifyChatListeners(NotifyChatAction.NOTIFY_CHAT_ACTION_CONNECTION_ERROR, "Socket Type: " + mSocketType + "accept() failed"); 621 | } 622 | } 623 | 624 | public void end(){ 625 | mEnd = true; 626 | } 627 | } 628 | } 629 | 630 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/bluetoothchat/BluetoothChatService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.android.bluetoothchat; 18 | 19 | import android.bluetooth.BluetoothAdapter; 20 | import android.bluetooth.BluetoothDevice; 21 | import android.bluetooth.BluetoothServerSocket; 22 | import android.bluetooth.BluetoothSocket; 23 | import android.content.Context; 24 | import android.os.Bundle; 25 | import android.os.Handler; 26 | import android.os.Message; 27 | 28 | import com.example.android.common.logger.Log; 29 | 30 | import java.io.IOException; 31 | import java.io.InputStream; 32 | import java.io.OutputStream; 33 | import java.util.UUID; 34 | 35 | /** 36 | * This class does all the work for setting up and managing Bluetooth 37 | * connections with other devices. It has a thread that listens for 38 | * incoming connections, a thread for connecting with a device, and a 39 | * thread for performing data transmissions when connected. 40 | */ 41 | public class BluetoothChatService { 42 | // Debugging 43 | private static final String TAG = "BluetoothChatService"; 44 | 45 | // Name for the SDP record when creating server socket 46 | private static final String NAME_SECURE = "BluetoothChatSecure"; 47 | private static final String NAME_INSECURE = "BluetoothChatInsecure"; 48 | 49 | // Unique UUID for this application 50 | private static final UUID MY_UUID_SECURE = 51 | UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); 52 | private static final UUID MY_UUID_INSECURE = 53 | UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); 54 | 55 | // Member fields 56 | private final BluetoothAdapter mAdapter; 57 | private final Handler mHandler; 58 | private AcceptThread mSecureAcceptThread; 59 | private AcceptThread mInsecureAcceptThread; 60 | private ConnectThread mConnectThread; 61 | private ConnectedThread mConnectedThread; 62 | private int mState; 63 | 64 | // Constants that indicate the current connection state 65 | public static final int STATE_NONE = 0; // we're doing nothing 66 | public static final int STATE_LISTEN = 1; // now listening for incoming connections 67 | public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection 68 | public static final int STATE_CONNECTED = 3; // now connected to a remote device 69 | 70 | /** 71 | * Constructor. Prepares a new BluetoothChat session. 72 | * 73 | * @param context The UI Activity Context 74 | * @param handler A Handler to send messages back to the UI Activity 75 | */ 76 | public BluetoothChatService(Context context, Handler handler) { 77 | mAdapter = BluetoothAdapter.getDefaultAdapter(); 78 | mState = STATE_NONE; 79 | mHandler = handler; 80 | } 81 | 82 | /** 83 | * Set the current state of the chat connection 84 | * 85 | * @param state An integer defining the current connection state 86 | */ 87 | private synchronized void setState(int state) { 88 | Log.d(TAG, "setState() " + mState + " -> " + state); 89 | mState = state; 90 | 91 | // Give the new state to the Handler so the UI Activity can update 92 | mHandler.obtainMessage(Constants.MESSAGE_STATE_CHANGE, state, -1).sendToTarget(); 93 | } 94 | 95 | /** 96 | * Return the current connection state. 97 | */ 98 | public synchronized int getState() { 99 | return mState; 100 | } 101 | 102 | /** 103 | * Start the chat service. Specifically start AcceptThread to begin a 104 | * session in listening (server) mode. Called by the Activity onResume() 105 | */ 106 | public synchronized void start() { 107 | Log.d(TAG, "start"); 108 | 109 | // Cancel any thread attempting to make a connection 110 | if (mConnectThread != null) { 111 | mConnectThread.cancel(); 112 | mConnectThread = null; 113 | } 114 | 115 | // Cancel any thread currently running a connection 116 | if (mConnectedThread != null) { 117 | mConnectedThread.cancel(); 118 | mConnectedThread = null; 119 | } 120 | 121 | setState(STATE_LISTEN); 122 | 123 | // Start the thread to listen on a BluetoothServerSocket 124 | if (mSecureAcceptThread == null) { 125 | mSecureAcceptThread = new AcceptThread(true); 126 | mSecureAcceptThread.start(); 127 | } 128 | if (mInsecureAcceptThread == null) { 129 | mInsecureAcceptThread = new AcceptThread(false); 130 | mInsecureAcceptThread.start(); 131 | } 132 | 133 | /* Automatically Scanning for BT devices running our app */ 134 | 135 | } 136 | 137 | /** 138 | * Start the ConnectThread to initiate a connection to a remote device. 139 | * 140 | * @param device The BluetoothDevice to connect 141 | * @param secure Socket Security type - Secure (true) , Insecure (false) 142 | */ 143 | public synchronized void connect(BluetoothDevice device, boolean secure) { 144 | Log.d(TAG, "connect to: " + device); 145 | 146 | // Cancel any thread attempting to make a connection 147 | if (mState == STATE_CONNECTING) { 148 | if (mConnectThread != null) { 149 | mConnectThread.cancel(); 150 | mConnectThread = null; 151 | } 152 | } 153 | 154 | // Cancel any thread currently running a connection 155 | if (mConnectedThread != null) { 156 | mConnectedThread.cancel(); 157 | mConnectedThread = null; 158 | } 159 | 160 | // Start the thread to connect with the given device 161 | mConnectThread = new ConnectThread(device, secure); 162 | mConnectThread.start(); 163 | setState(STATE_CONNECTING); 164 | } 165 | 166 | /** 167 | * Start the ConnectedThread to begin managing a Bluetooth connection 168 | * 169 | * @param socket The BluetoothSocket on which the connection was made 170 | * @param device The BluetoothDevice that has been connected 171 | */ 172 | public synchronized void connected(BluetoothSocket socket, BluetoothDevice 173 | device, final String socketType, Constants.ROLE role) { 174 | Log.d(TAG, "connected, Socket Type:" + socketType); 175 | 176 | // Cancel the thread that completed the connection 177 | if (mConnectThread != null) { 178 | mConnectThread.cancel(); 179 | mConnectThread = null; 180 | } 181 | 182 | // Cancel any thread currently running a connection 183 | if (mConnectedThread != null) { 184 | mConnectedThread.cancel(); 185 | mConnectedThread = null; 186 | } 187 | 188 | // Cancel the accept thread because we only want to connect to one device 189 | if (mSecureAcceptThread != null) { 190 | mSecureAcceptThread.cancel(); 191 | mSecureAcceptThread = null; 192 | } 193 | if (mInsecureAcceptThread != null) { 194 | mInsecureAcceptThread.cancel(); 195 | mInsecureAcceptThread = null; 196 | } 197 | 198 | // Start the thread to manage the connection and perform transmissions 199 | mConnectedThread = new ConnectedThread(socket, socketType); 200 | mConnectedThread.start(); 201 | 202 | // Send the name of the connected device back to the UI Activity 203 | Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME); 204 | Bundle bundle = new Bundle(); 205 | bundle.putString(Constants.DEVICE_NAME, device.getName()); 206 | msg.setData(bundle); 207 | mHandler.sendMessage(msg); 208 | 209 | setState(STATE_CONNECTED); 210 | 211 | /* Automatic ping-pong conversation */ 212 | /*if(role == Constants.ROLE.CLIENT) { 213 | write((new String("PING")).getBytes()); 214 | }*/ 215 | 216 | } 217 | 218 | /** 219 | * Stop all threads 220 | */ 221 | public synchronized void stop() { 222 | Log.d(TAG, "stop"); 223 | 224 | if (mConnectThread != null) { 225 | mConnectThread.cancel(); 226 | mConnectThread = null; 227 | } 228 | 229 | if (mConnectedThread != null) { 230 | mConnectedThread.cancel(); 231 | mConnectedThread = null; 232 | } 233 | 234 | if (mSecureAcceptThread != null) { 235 | mSecureAcceptThread.cancel(); 236 | mSecureAcceptThread = null; 237 | } 238 | 239 | if (mInsecureAcceptThread != null) { 240 | mInsecureAcceptThread.cancel(); 241 | mInsecureAcceptThread = null; 242 | } 243 | setState(STATE_NONE); 244 | } 245 | 246 | /** 247 | * Write to the ConnectedThread in an unsynchronized manner 248 | * 249 | * @param out The bytes to write 250 | * @see ConnectedThread#write(byte[]) 251 | */ 252 | public void write(byte[] out) { 253 | // Create temporary object 254 | ConnectedThread r; 255 | // Synchronize a copy of the ConnectedThread 256 | synchronized (this) { 257 | if (mState != STATE_CONNECTED) return; 258 | r = mConnectedThread; 259 | } 260 | // Perform the write unsynchronized 261 | r.write(out); 262 | } 263 | 264 | /** 265 | * Indicate that the connection attempt failed and notify the UI Activity. 266 | */ 267 | private void connectionFailed() { 268 | // Send a failure message back to the Activity 269 | Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST); 270 | Bundle bundle = new Bundle(); 271 | bundle.putString(Constants.TOAST, "Unable to connect device"); 272 | msg.setData(bundle); 273 | mHandler.sendMessage(msg); 274 | 275 | // Start the service over to restart listening mode 276 | BluetoothChatService.this.start(); 277 | } 278 | 279 | /** 280 | * Indicate that the connection was lost and notify the UI Activity. 281 | */ 282 | private void connectionLost() { 283 | // Send a failure message back to the Activity 284 | Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST); 285 | Bundle bundle = new Bundle(); 286 | bundle.putString(Constants.TOAST, "Device connection was lost"); 287 | msg.setData(bundle); 288 | mHandler.sendMessage(msg); 289 | 290 | // Start the service over to restart listening mode 291 | //BluetoothChatService.this.start(); 292 | } 293 | 294 | 295 | private void reconnect(){ 296 | Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST); 297 | Bundle bundle = new Bundle(); 298 | bundle.putString(Constants.TOAST, "Trying to reconnect..."); 299 | msg.setData(bundle); 300 | mHandler.sendMessage(msg); 301 | 302 | } 303 | 304 | /** 305 | * This thread runs while listening for incoming connections. It behaves 306 | * like a server-side client. It runs until a connection is accepted 307 | * (or until cancelled). 308 | */ 309 | private class AcceptThread extends Thread { 310 | // The local server socket 311 | private final BluetoothServerSocket mmServerSocket; 312 | private String mSocketType; 313 | 314 | public AcceptThread(boolean secure) { 315 | BluetoothServerSocket tmp = null; 316 | mSocketType = secure ? "Secure" : "Insecure"; 317 | 318 | // Create a new listening server socket 319 | try { 320 | if (secure) { 321 | tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, 322 | MY_UUID_SECURE); 323 | } else { 324 | tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord( 325 | NAME_INSECURE, MY_UUID_INSECURE); 326 | } 327 | } catch (IOException e) { 328 | Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e); 329 | } 330 | mmServerSocket = tmp; 331 | } 332 | 333 | public void run() { 334 | Log.d(TAG, "Socket Type: " + mSocketType + 335 | "BEGIN mAcceptThread" + this); 336 | setName("AcceptThread" + mSocketType); 337 | 338 | BluetoothSocket socket = null; 339 | 340 | // Listen to the server socket if we're not connected 341 | while (mState != STATE_CONNECTED) { 342 | try { 343 | // This is a blocking call and will only return on a 344 | // successful connection or an exception 345 | socket = mmServerSocket.accept(); 346 | } catch (IOException e) { 347 | Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e); 348 | break; 349 | } 350 | 351 | // If a connection was accepted 352 | if (socket != null) { 353 | synchronized (BluetoothChatService.this) { 354 | switch (mState) { 355 | case STATE_LISTEN: 356 | case STATE_CONNECTING: 357 | // Situation normal. Start the connected thread. 358 | connected(socket, socket.getRemoteDevice(), 359 | mSocketType, Constants.ROLE.SERVER); 360 | break; 361 | case STATE_NONE: 362 | case STATE_CONNECTED: 363 | // Either not ready or already connected. Terminate new socket. 364 | try { 365 | socket.close(); 366 | } catch (IOException e) { 367 | Log.e(TAG, "Could not close unwanted socket", e); 368 | } 369 | break; 370 | } 371 | } 372 | } 373 | } 374 | Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType); 375 | 376 | } 377 | 378 | public void cancel() { 379 | Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this); 380 | try { 381 | mmServerSocket.close(); 382 | } catch (IOException e) { 383 | Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e); 384 | } 385 | } 386 | } 387 | 388 | 389 | /** 390 | * This thread runs while attempting to make an outgoing connection 391 | * with a device. It runs straight through; the connection either 392 | * succeeds or fails. 393 | */ 394 | private class ConnectThread extends Thread { 395 | private final BluetoothSocket mmSocket; 396 | private final BluetoothDevice mmDevice; 397 | private String mSocketType; 398 | 399 | public ConnectThread(BluetoothDevice device, boolean secure) { 400 | mmDevice = device; 401 | BluetoothSocket tmp = null; 402 | mSocketType = secure ? "Secure" : "Insecure"; 403 | 404 | // Get a BluetoothSocket for a connection with the 405 | // given BluetoothDevice 406 | try { 407 | if (secure) { 408 | tmp = device.createRfcommSocketToServiceRecord( 409 | MY_UUID_SECURE); 410 | } else { 411 | tmp = device.createInsecureRfcommSocketToServiceRecord( 412 | MY_UUID_INSECURE); 413 | } 414 | } catch (IOException e) { 415 | Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e); 416 | } 417 | mmSocket = tmp; 418 | } 419 | 420 | public void run() { 421 | Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType); 422 | setName("ConnectThread" + mSocketType); 423 | 424 | // Always cancel discovery because it will slow down a connection 425 | mAdapter.cancelDiscovery(); 426 | 427 | // Make a connection to the BluetoothSocket 428 | try { 429 | // This is a blocking call and will only return on a 430 | // successful connection or an exception 431 | mmSocket.connect(); 432 | } catch (IOException e) { 433 | // Close the socket 434 | try { 435 | mmSocket.close(); 436 | } catch (IOException e2) { 437 | Log.e(TAG, "unable to close() " + mSocketType + 438 | " socket during connection failure", e2); 439 | } 440 | connectionFailed(); 441 | return; 442 | } 443 | 444 | // Reset the ConnectThread because we're done 445 | synchronized (BluetoothChatService.this) { 446 | mConnectThread = null; 447 | } 448 | 449 | // Start the connected thread 450 | connected(mmSocket, mmDevice, mSocketType, Constants.ROLE.CLIENT); 451 | } 452 | 453 | public void cancel() { 454 | try { 455 | mmSocket.close(); 456 | } catch (IOException e) { 457 | Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e); 458 | } 459 | } 460 | } 461 | 462 | /** 463 | * This thread runs during a connection with a remote device. 464 | * It handles all incoming and outgoing transmissions. 465 | */ 466 | private class ConnectedThread extends Thread { 467 | private final BluetoothSocket mmSocket; 468 | private final InputStream mmInStream; 469 | private final OutputStream mmOutStream; 470 | 471 | public ConnectedThread(BluetoothSocket socket, String socketType) { 472 | Log.d(TAG, "create ConnectedThread: " + socketType); 473 | mmSocket = socket; 474 | InputStream tmpIn = null; 475 | OutputStream tmpOut = null; 476 | 477 | // Get the BluetoothSocket input and output streams 478 | try { 479 | tmpIn = socket.getInputStream(); 480 | tmpOut = socket.getOutputStream(); 481 | } catch (IOException e) { 482 | Log.e(TAG, "temp sockets not created", e); 483 | } 484 | 485 | mmInStream = tmpIn; 486 | mmOutStream = tmpOut; 487 | } 488 | 489 | public void run() { 490 | Log.i(TAG, "BEGIN mConnectedThread"); 491 | byte[] buffer = new byte[1024]; 492 | int bytes; 493 | 494 | // Keep listening to the InputStream while connected 495 | while (true) { 496 | try { 497 | // Read from the InputStream 498 | bytes = mmInStream.read(buffer); 499 | 500 | // Send the obtained bytes to the UI Activity 501 | mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer) 502 | .sendToTarget(); 503 | } catch (IOException e) { 504 | Log.e(TAG, "disconnected", e); 505 | connectionLost(); 506 | // Start the service over to restart listening mode 507 | BluetoothChatService.this.start(); 508 | //reconnect(); 509 | break; 510 | } 511 | } 512 | } 513 | 514 | /** 515 | * Write to the connected OutStream. 516 | * 517 | * @param buffer The bytes to write 518 | */ 519 | public void write(byte[] buffer) { 520 | try { 521 | mmOutStream.write(buffer); 522 | 523 | // Share the sent message back to the UI Activity 524 | mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer) 525 | .sendToTarget(); 526 | } catch (IOException e) { 527 | Log.e(TAG, "Exception during write", e); 528 | } 529 | } 530 | 531 | public void cancel() { 532 | try { 533 | mmSocket.close(); 534 | } catch (IOException e) { 535 | Log.e(TAG, "close() of connect socket failed", e); 536 | } 537 | } 538 | } 539 | } 540 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/bluetoothchat/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.android.bluetoothchat; 18 | 19 | /** 20 | * Defines several constants used between {@link BluetoothChatService} and the UI. 21 | */ 22 | public interface Constants { 23 | 24 | // Message types sent from the BluetoothChatService Handler 25 | public static final int MESSAGE_STATE_CHANGE = 1; 26 | public static final int MESSAGE_READ = 2; 27 | public static final int MESSAGE_WRITE = 3; 28 | public static final int MESSAGE_DEVICE_NAME = 4; 29 | public static final int MESSAGE_TOAST = 5; 30 | public static final int MESSAGE_TOAST_FAST = 6; 31 | 32 | // Key names received from the BluetoothChatService Handler 33 | public static final String DEVICE_NAME = "device_name"; 34 | public static final String TOAST = "toast"; 35 | public static enum ROLE { 36 | SERVER, 37 | CLIENT 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/bluetoothchat/DeviceListActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.android.bluetoothchat; 18 | 19 | import android.app.Activity; 20 | import android.support.v4.app.Fragment; 21 | import android.bluetooth.BluetoothAdapter; 22 | import android.bluetooth.BluetoothDevice; 23 | import android.content.BroadcastReceiver; 24 | import android.content.Context; 25 | import android.content.Intent; 26 | import android.content.IntentFilter; 27 | import android.os.Bundle; 28 | import android.support.v4.app.FragmentActivity; 29 | import android.view.View; 30 | import android.view.Window; 31 | import android.widget.AdapterView; 32 | import android.widget.ArrayAdapter; 33 | import android.widget.Button; 34 | import android.widget.ListView; 35 | import android.widget.TextView; 36 | 37 | import com.example.android.common.logger.Log; 38 | 39 | import java.util.Set; 40 | 41 | /** 42 | * This Activity appears as a dialog. It lists any paired devices and 43 | * devices detected in the area after discovery. When a device is chosen 44 | * by the user, the MAC address of the device is sent back to the parent 45 | * Activity in the result Intent. 46 | */ 47 | public class DeviceListActivity extends FragmentActivity { 48 | 49 | /** 50 | * Tag for Log 51 | */ 52 | private static final String TAG = "DeviceListActivity"; 53 | 54 | /** 55 | * Return Intent extra 56 | */ 57 | public static String EXTRA_DEVICE_ADDRESS = "device_address"; 58 | 59 | /** 60 | * Member fields 61 | */ 62 | private BluetoothAdapter mBtAdapter; 63 | 64 | /** 65 | * Newly discovered devices 66 | */ 67 | private ArrayAdapter mNewDevicesArrayAdapter; 68 | 69 | 70 | @Override 71 | protected void onCreate(Bundle savedInstanceState) { 72 | super.onCreate(savedInstanceState); 73 | 74 | // Setup the window 75 | requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); 76 | setContentView(R.layout.activity_device_list); 77 | 78 | // Set result CANCELED in case the user backs out 79 | setResult(Activity.RESULT_CANCELED); 80 | 81 | // Initialize the button to perform device discovery 82 | Button scanButton = (Button) findViewById(R.id.button_scan); 83 | scanButton.setOnClickListener(new View.OnClickListener() { 84 | public void onClick(View v) { 85 | doDiscovery(); 86 | v.setVisibility(View.GONE); 87 | } 88 | }); 89 | 90 | // Initialize array adapters. One for already paired devices and 91 | // one for newly discovered devices 92 | ArrayAdapter pairedDevicesArrayAdapter = 93 | new ArrayAdapter(this, R.layout.device_name); 94 | mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); 95 | 96 | // Find and set up the ListView for paired devices 97 | ListView pairedListView = (ListView) findViewById(R.id.paired_devices); 98 | pairedListView.setAdapter(pairedDevicesArrayAdapter); 99 | pairedListView.setOnItemClickListener(mDeviceClickListener); 100 | 101 | // Find and set up the ListView for newly discovered devices 102 | ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); 103 | newDevicesListView.setAdapter(mNewDevicesArrayAdapter); 104 | newDevicesListView.setOnItemClickListener(mDeviceClickListener); 105 | 106 | // Register for broadcasts when a device is discovered 107 | IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 108 | this.registerReceiver(mReceiver, filter); 109 | 110 | // Register for broadcasts when discovery has finished 111 | filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 112 | this.registerReceiver(mReceiver, filter); 113 | 114 | // Get the local Bluetooth adapter 115 | mBtAdapter = BluetoothAdapter.getDefaultAdapter(); 116 | 117 | // Get a set of currently paired devices 118 | Set pairedDevices = mBtAdapter.getBondedDevices(); 119 | 120 | // If there are paired devices, add each one to the ArrayAdapter 121 | if (pairedDevices.size() > 0) { 122 | findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); 123 | for (BluetoothDevice device : pairedDevices) { 124 | pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 125 | } 126 | } else { 127 | String noDevices = getResources().getText(R.string.none_paired).toString(); 128 | pairedDevicesArrayAdapter.add(noDevices); 129 | } 130 | } 131 | 132 | @Override 133 | protected void onDestroy() { 134 | super.onDestroy(); 135 | 136 | // Make sure we're not doing discovery anymore 137 | if (mBtAdapter != null) { 138 | mBtAdapter.cancelDiscovery(); 139 | } 140 | 141 | // Unregister broadcast listeners 142 | this.unregisterReceiver(mReceiver); 143 | } 144 | 145 | 146 | /** 147 | * Start device discover with the BluetoothAdapter 148 | */ 149 | private void doDiscovery() { 150 | Log.d(TAG, "doDiscovery()"); 151 | 152 | // Indicate scanning in the title 153 | setProgressBarIndeterminateVisibility(true); 154 | setTitle(R.string.scanning); 155 | 156 | // Turn on sub-title for new devices 157 | findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); 158 | 159 | // If we're already discovering, stop it 160 | if (mBtAdapter.isDiscovering()) { 161 | mBtAdapter.cancelDiscovery(); 162 | } 163 | 164 | // Request discover from BluetoothAdapter 165 | mBtAdapter.startDiscovery(); 166 | } 167 | 168 | /** 169 | * The on-click listener for all devices in the ListViews 170 | */ 171 | private AdapterView.OnItemClickListener mDeviceClickListener 172 | = new AdapterView.OnItemClickListener() { 173 | public void onItemClick(AdapterView av, View v, int arg2, long arg3) { 174 | // Cancel discovery because it's costly and we're about to connect 175 | mBtAdapter.cancelDiscovery(); 176 | 177 | // Get the device MAC address, which is the last 17 chars in the View 178 | String info = ((TextView) v).getText().toString(); 179 | String address = info.substring(info.length() - 17); 180 | 181 | // Create the result Intent and include the MAC address 182 | Intent intent = new Intent(); 183 | intent.putExtra(EXTRA_DEVICE_ADDRESS, address); 184 | 185 | // Set result and finish this Activity 186 | setResult(Activity.RESULT_OK, intent); 187 | finish(); 188 | } 189 | }; 190 | 191 | /** 192 | * The BroadcastReceiver that listens for discovered devices and changes the title when 193 | * discovery is finished 194 | */ 195 | private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 196 | @Override 197 | public void onReceive(Context context, Intent intent) { 198 | String action = intent.getAction(); 199 | 200 | // When discovery finds a device 201 | if (BluetoothDevice.ACTION_FOUND.equals(action)) { 202 | // Get the BluetoothDevice object from the Intent 203 | BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 204 | // If it's already paired, skip it, because it's been listed already 205 | if (device.getBondState() != BluetoothDevice.BOND_BONDED) { 206 | mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 207 | //tryToConnect(device); 208 | } 209 | // When discovery is finished, change the Activity title 210 | } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 211 | setProgressBarIndeterminateVisibility(false); 212 | setTitle(R.string.select_device); 213 | if (mNewDevicesArrayAdapter.getCount() == 0) { 214 | String noDevices = getResources().getText(R.string.none_found).toString(); 215 | mNewDevicesArrayAdapter.add(noDevices); 216 | } 217 | } 218 | } 219 | }; 220 | 221 | private void tryToConnect(BluetoothDevice device){ 222 | mBtAdapter.cancelDiscovery(); 223 | // Get the device MAC address, which is the last 17 chars in the View 224 | String address = device.getAddress(); 225 | // Create the result Intent and include the MAC address 226 | Intent intent = new Intent(); 227 | intent.putExtra(EXTRA_DEVICE_ADDRESS, address); 228 | // Set result and finish this Activity 229 | setResult(Activity.RESULT_OK, intent); 230 | finish(); 231 | } 232 | 233 | } 234 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/bluetoothchat/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.example.android.bluetoothchat; 19 | 20 | import android.os.Bundle; 21 | import android.support.v4.app.FragmentTransaction; 22 | import android.view.Menu; 23 | import android.view.MenuItem; 24 | import android.widget.ViewAnimator; 25 | 26 | import com.example.android.common.activities.SampleActivityBase; 27 | import com.example.android.common.logger.Log; 28 | import com.example.android.common.logger.LogFragment; 29 | import com.example.android.common.logger.LogWrapper; 30 | import com.example.android.common.logger.MessageOnlyLogFilter; 31 | 32 | /** 33 | * A simple launcher activity containing a summary sample description, sample log and a custom 34 | * {@link android.support.v4.app.Fragment} which can display a view. 35 | *

36 | * For devices with displays with a width of 720dp or greater, the sample log is always visible, 37 | * on other devices it's visibility is controlled by an item on the Action Bar. 38 | */ 39 | public class MainActivity extends SampleActivityBase { 40 | 41 | public static final String TAG = "MainActivity"; 42 | 43 | // Whether the Log Fragment is currently shown 44 | private boolean mLogShown; 45 | 46 | @Override 47 | protected void onCreate(Bundle savedInstanceState) { 48 | super.onCreate(savedInstanceState); 49 | setContentView(R.layout.activity_main); 50 | 51 | if (savedInstanceState == null) { 52 | FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 53 | BluetoothChatFragment fragment = new BluetoothChatFragment(); 54 | transaction.replace(R.id.sample_content_fragment, fragment); 55 | transaction.commit(); 56 | } 57 | } 58 | 59 | @Override 60 | public boolean onCreateOptionsMenu(Menu menu) { 61 | getMenuInflater().inflate(R.menu.main, menu); 62 | return true; 63 | } 64 | 65 | @Override 66 | public boolean onPrepareOptionsMenu(Menu menu) { 67 | MenuItem logToggle = menu.findItem(R.id.menu_toggle_log); 68 | logToggle.setVisible(findViewById(R.id.sample_output) instanceof ViewAnimator); 69 | logToggle.setTitle(mLogShown ? R.string.sample_hide_log : R.string.sample_show_log); 70 | 71 | return super.onPrepareOptionsMenu(menu); 72 | } 73 | 74 | @Override 75 | public boolean onOptionsItemSelected(MenuItem item) { 76 | switch(item.getItemId()) { 77 | case R.id.menu_toggle_log: 78 | mLogShown = !mLogShown; 79 | ViewAnimator output = (ViewAnimator) findViewById(R.id.sample_output); 80 | if (mLogShown) { 81 | output.setDisplayedChild(1); 82 | } else { 83 | output.setDisplayedChild(0); 84 | } 85 | supportInvalidateOptionsMenu(); 86 | return true; 87 | } 88 | return super.onOptionsItemSelected(item); 89 | } 90 | 91 | /** Create a chain of targets that will receive log data */ 92 | @Override 93 | public void initializeLogging() { 94 | // Wraps Android's native log framework. 95 | LogWrapper logWrapper = new LogWrapper(); 96 | // Using Log, front-end to the logging chain, emulates android.util.log method signatures. 97 | Log.setLogNode(logWrapper); 98 | 99 | // Filter strips out everything except the message text. 100 | MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter(); 101 | logWrapper.setNext(msgFilter); 102 | 103 | // On screen logging via a fragment with a TextView. 104 | LogFragment logFragment = (LogFragment) getSupportFragmentManager() 105 | .findFragmentById(R.id.log_fragment); 106 | msgFilter.setNext(logFragment.getLogView()); 107 | 108 | Log.i(TAG, "Ready"); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/activities/SampleActivityBase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.android.common.activities; 18 | 19 | import android.os.Bundle; 20 | import android.support.v4.app.FragmentActivity; 21 | 22 | import com.example.android.common.logger.Log; 23 | import com.example.android.common.logger.LogWrapper; 24 | 25 | /** 26 | * Base launcher activity, to handle most of the common plumbing for samples. 27 | */ 28 | public class SampleActivityBase extends FragmentActivity { 29 | 30 | public static final String TAG = "SampleActivityBase"; 31 | 32 | @Override 33 | protected void onCreate(Bundle savedInstanceState) { 34 | super.onCreate(savedInstanceState); 35 | } 36 | 37 | @Override 38 | protected void onStart() { 39 | super.onStart(); 40 | initializeLogging(); 41 | } 42 | 43 | /** Set up targets to receive log data */ 44 | public void initializeLogging() { 45 | // Using Log, front-end to the logging chain, emulates android.util.log method signatures. 46 | // Wraps Android's native log framework 47 | LogWrapper logWrapper = new LogWrapper(); 48 | Log.setLogNode(logWrapper); 49 | 50 | Log.i(TAG, "Ready"); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/Log.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.android.common.logger; 17 | 18 | /** 19 | * Helper class for a list (or tree) of LoggerNodes. 20 | * 21 | *

When this is set as the head of the list, 22 | * an instance of it can function as a drop-in replacement for {@link android.util.Log}. 23 | * Most of the methods in this class server only to map a method call in Log to its equivalent 24 | * in LogNode.

25 | */ 26 | public class Log { 27 | // Grabbing the native values from Android's native logging facilities, 28 | // to make for easy migration and interop. 29 | public static final int NONE = -1; 30 | public static final int VERBOSE = android.util.Log.VERBOSE; 31 | public static final int DEBUG = android.util.Log.DEBUG; 32 | public static final int INFO = android.util.Log.INFO; 33 | public static final int WARN = android.util.Log.WARN; 34 | public static final int ERROR = android.util.Log.ERROR; 35 | public static final int ASSERT = android.util.Log.ASSERT; 36 | 37 | // Stores the beginning of the LogNode topology. 38 | private static LogNode mLogNode; 39 | 40 | /** 41 | * Returns the next LogNode in the linked list. 42 | */ 43 | public static LogNode getLogNode() { 44 | return mLogNode; 45 | } 46 | 47 | /** 48 | * Sets the LogNode data will be sent to. 49 | */ 50 | public static void setLogNode(LogNode node) { 51 | mLogNode = node; 52 | } 53 | 54 | /** 55 | * Instructs the LogNode to print the log data provided. Other LogNodes can 56 | * be chained to the end of the LogNode as desired. 57 | * 58 | * @param priority Log level of the data being logged. Verbose, Error, etc. 59 | * @param tag Tag for for the log data. Can be used to organize log statements. 60 | * @param msg The actual message to be logged. 61 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 62 | * to extract and print useful information. 63 | */ 64 | public static void println(int priority, String tag, String msg, Throwable tr) { 65 | if (mLogNode != null) { 66 | mLogNode.println(priority, tag, msg, tr); 67 | } 68 | } 69 | 70 | /** 71 | * Instructs the LogNode to print the log data provided. Other LogNodes can 72 | * be chained to the end of the LogNode as desired. 73 | * 74 | * @param priority Log level of the data being logged. Verbose, Error, etc. 75 | * @param tag Tag for for the log data. Can be used to organize log statements. 76 | * @param msg The actual message to be logged. The actual message to be logged. 77 | */ 78 | public static void println(int priority, String tag, String msg) { 79 | println(priority, tag, msg, null); 80 | } 81 | 82 | /** 83 | * Prints a message at VERBOSE priority. 84 | * 85 | * @param tag Tag for for the log data. Can be used to organize log statements. 86 | * @param msg The actual message to be logged. 87 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 88 | * to extract and print useful information. 89 | */ 90 | public static void v(String tag, String msg, Throwable tr) { 91 | println(VERBOSE, tag, msg, tr); 92 | } 93 | 94 | /** 95 | * Prints a message at VERBOSE priority. 96 | * 97 | * @param tag Tag for for the log data. Can be used to organize log statements. 98 | * @param msg The actual message to be logged. 99 | */ 100 | public static void v(String tag, String msg) { 101 | v(tag, msg, null); 102 | } 103 | 104 | 105 | /** 106 | * Prints a message at DEBUG priority. 107 | * 108 | * @param tag Tag for for the log data. Can be used to organize log statements. 109 | * @param msg The actual message to be logged. 110 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 111 | * to extract and print useful information. 112 | */ 113 | public static void d(String tag, String msg, Throwable tr) { 114 | println(DEBUG, tag, msg, tr); 115 | } 116 | 117 | /** 118 | * Prints a message at DEBUG priority. 119 | * 120 | * @param tag Tag for for the log data. Can be used to organize log statements. 121 | * @param msg The actual message to be logged. 122 | */ 123 | public static void d(String tag, String msg) { 124 | d(tag, msg, null); 125 | } 126 | 127 | /** 128 | * Prints a message at INFO priority. 129 | * 130 | * @param tag Tag for for the log data. Can be used to organize log statements. 131 | * @param msg The actual message to be logged. 132 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 133 | * to extract and print useful information. 134 | */ 135 | public static void i(String tag, String msg, Throwable tr) { 136 | println(INFO, tag, msg, tr); 137 | } 138 | 139 | /** 140 | * Prints a message at INFO priority. 141 | * 142 | * @param tag Tag for for the log data. Can be used to organize log statements. 143 | * @param msg The actual message to be logged. 144 | */ 145 | public static void i(String tag, String msg) { 146 | i(tag, msg, null); 147 | } 148 | 149 | /** 150 | * Prints a message at WARN priority. 151 | * 152 | * @param tag Tag for for the log data. Can be used to organize log statements. 153 | * @param msg The actual message to be logged. 154 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 155 | * to extract and print useful information. 156 | */ 157 | public static void w(String tag, String msg, Throwable tr) { 158 | println(WARN, tag, msg, tr); 159 | } 160 | 161 | /** 162 | * Prints a message at WARN priority. 163 | * 164 | * @param tag Tag for for the log data. Can be used to organize log statements. 165 | * @param msg The actual message to be logged. 166 | */ 167 | public static void w(String tag, String msg) { 168 | w(tag, msg, null); 169 | } 170 | 171 | /** 172 | * Prints a message at WARN priority. 173 | * 174 | * @param tag Tag for for the log data. Can be used to organize log statements. 175 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 176 | * to extract and print useful information. 177 | */ 178 | public static void w(String tag, Throwable tr) { 179 | w(tag, null, tr); 180 | } 181 | 182 | /** 183 | * Prints a message at ERROR priority. 184 | * 185 | * @param tag Tag for for the log data. Can be used to organize log statements. 186 | * @param msg The actual message to be logged. 187 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 188 | * to extract and print useful information. 189 | */ 190 | public static void e(String tag, String msg, Throwable tr) { 191 | println(ERROR, tag, msg, tr); 192 | } 193 | 194 | /** 195 | * Prints a message at ERROR priority. 196 | * 197 | * @param tag Tag for for the log data. Can be used to organize log statements. 198 | * @param msg The actual message to be logged. 199 | */ 200 | public static void e(String tag, String msg) { 201 | e(tag, msg, null); 202 | } 203 | 204 | /** 205 | * Prints a message at ASSERT priority. 206 | * 207 | * @param tag Tag for for the log data. Can be used to organize log statements. 208 | * @param msg The actual message to be logged. 209 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 210 | * to extract and print useful information. 211 | */ 212 | public static void wtf(String tag, String msg, Throwable tr) { 213 | println(ASSERT, tag, msg, tr); 214 | } 215 | 216 | /** 217 | * Prints a message at ASSERT priority. 218 | * 219 | * @param tag Tag for for the log data. Can be used to organize log statements. 220 | * @param msg The actual message to be logged. 221 | */ 222 | public static void wtf(String tag, String msg) { 223 | wtf(tag, msg, null); 224 | } 225 | 226 | /** 227 | * Prints a message at ASSERT priority. 228 | * 229 | * @param tag Tag for for the log data. Can be used to organize log statements. 230 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 231 | * to extract and print useful information. 232 | */ 233 | public static void wtf(String tag, Throwable tr) { 234 | wtf(tag, null, tr); 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/LogFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | /* 17 | * Copyright 2013 The Android Open Source Project 18 | * 19 | * Licensed under the Apache License, Version 2.0 (the "License"); 20 | * you may not use this file except in compliance with the License. 21 | * You may obtain a copy of the License at 22 | * 23 | * http://www.apache.org/licenses/LICENSE-2.0 24 | * 25 | * Unless required by applicable law or agreed to in writing, software 26 | * distributed under the License is distributed on an "AS IS" BASIS, 27 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 28 | * See the License for the specific language governing permissions and 29 | * limitations under the License. 30 | */ 31 | 32 | package com.example.android.common.logger; 33 | 34 | import android.graphics.Typeface; 35 | import android.os.Bundle; 36 | import android.support.v4.app.Fragment; 37 | import android.text.Editable; 38 | import android.text.TextWatcher; 39 | import android.view.Gravity; 40 | import android.view.LayoutInflater; 41 | import android.view.View; 42 | import android.view.ViewGroup; 43 | import android.widget.ScrollView; 44 | 45 | /** 46 | * Simple fraggment which contains a LogView and uses is to output log data it receives 47 | * through the LogNode interface. 48 | */ 49 | public class LogFragment extends Fragment { 50 | 51 | private LogView mLogView; 52 | private ScrollView mScrollView; 53 | 54 | public LogFragment() {} 55 | 56 | public View inflateViews() { 57 | mScrollView = new ScrollView(getActivity()); 58 | ViewGroup.LayoutParams scrollParams = new ViewGroup.LayoutParams( 59 | ViewGroup.LayoutParams.MATCH_PARENT, 60 | ViewGroup.LayoutParams.MATCH_PARENT); 61 | mScrollView.setLayoutParams(scrollParams); 62 | 63 | mLogView = new LogView(getActivity()); 64 | ViewGroup.LayoutParams logParams = new ViewGroup.LayoutParams(scrollParams); 65 | logParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; 66 | mLogView.setLayoutParams(logParams); 67 | mLogView.setClickable(true); 68 | mLogView.setFocusable(true); 69 | mLogView.setTypeface(Typeface.MONOSPACE); 70 | 71 | // Want to set padding as 16 dips, setPadding takes pixels. Hooray math! 72 | int paddingDips = 16; 73 | double scale = getResources().getDisplayMetrics().density; 74 | int paddingPixels = (int) ((paddingDips * (scale)) + .5); 75 | mLogView.setPadding(paddingPixels, paddingPixels, paddingPixels, paddingPixels); 76 | mLogView.setCompoundDrawablePadding(paddingPixels); 77 | 78 | mLogView.setGravity(Gravity.BOTTOM); 79 | mLogView.setTextAppearance(getActivity(), android.R.style.TextAppearance_Holo_Medium); 80 | 81 | mScrollView.addView(mLogView); 82 | return mScrollView; 83 | } 84 | 85 | @Override 86 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 87 | Bundle savedInstanceState) { 88 | 89 | View result = inflateViews(); 90 | 91 | mLogView.addTextChangedListener(new TextWatcher() { 92 | @Override 93 | public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 94 | 95 | @Override 96 | public void onTextChanged(CharSequence s, int start, int before, int count) {} 97 | 98 | @Override 99 | public void afterTextChanged(Editable s) { 100 | mScrollView.fullScroll(ScrollView.FOCUS_DOWN); 101 | } 102 | }); 103 | return result; 104 | } 105 | 106 | public LogView getLogView() { 107 | return mLogView; 108 | } 109 | } -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/LogNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.android.common.logger; 17 | 18 | /** 19 | * Basic interface for a logging system that can output to one or more targets. 20 | * Note that in addition to classes that will output these logs in some format, 21 | * one can also implement this interface over a filter and insert that in the chain, 22 | * such that no targets further down see certain data, or see manipulated forms of the data. 23 | * You could, for instance, write a "ToHtmlLoggerNode" that just converted all the log data 24 | * it received to HTML and sent it along to the next node in the chain, without printing it 25 | * anywhere. 26 | */ 27 | public interface LogNode { 28 | 29 | /** 30 | * Instructs first LogNode in the list to print the log data provided. 31 | * @param priority Log level of the data being logged. Verbose, Error, etc. 32 | * @param tag Tag for for the log data. Can be used to organize log statements. 33 | * @param msg The actual message to be logged. The actual message to be logged. 34 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 35 | * to extract and print useful information. 36 | */ 37 | public void println(int priority, String tag, String msg, Throwable tr); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/LogView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.android.common.logger; 17 | 18 | import android.app.Activity; 19 | import android.content.Context; 20 | import android.util.*; 21 | import android.widget.TextView; 22 | 23 | /** Simple TextView which is used to output log data received through the LogNode interface. 24 | */ 25 | public class LogView extends TextView implements LogNode { 26 | 27 | public LogView(Context context) { 28 | super(context); 29 | } 30 | 31 | public LogView(Context context, AttributeSet attrs) { 32 | super(context, attrs); 33 | } 34 | 35 | public LogView(Context context, AttributeSet attrs, int defStyle) { 36 | super(context, attrs, defStyle); 37 | } 38 | 39 | /** 40 | * Formats the log data and prints it out to the LogView. 41 | * @param priority Log level of the data being logged. Verbose, Error, etc. 42 | * @param tag Tag for for the log data. Can be used to organize log statements. 43 | * @param msg The actual message to be logged. The actual message to be logged. 44 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 45 | * to extract and print useful information. 46 | */ 47 | @Override 48 | public void println(int priority, String tag, String msg, Throwable tr) { 49 | 50 | 51 | String priorityStr = null; 52 | 53 | // For the purposes of this View, we want to print the priority as readable text. 54 | switch(priority) { 55 | case android.util.Log.VERBOSE: 56 | priorityStr = "VERBOSE"; 57 | break; 58 | case android.util.Log.DEBUG: 59 | priorityStr = "DEBUG"; 60 | break; 61 | case android.util.Log.INFO: 62 | priorityStr = "INFO"; 63 | break; 64 | case android.util.Log.WARN: 65 | priorityStr = "WARN"; 66 | break; 67 | case android.util.Log.ERROR: 68 | priorityStr = "ERROR"; 69 | break; 70 | case android.util.Log.ASSERT: 71 | priorityStr = "ASSERT"; 72 | break; 73 | default: 74 | break; 75 | } 76 | 77 | // Handily, the Log class has a facility for converting a stack trace into a usable string. 78 | String exceptionStr = null; 79 | if (tr != null) { 80 | exceptionStr = android.util.Log.getStackTraceString(tr); 81 | } 82 | 83 | // Take the priority, tag, message, and exception, and concatenate as necessary 84 | // into one usable line of text. 85 | final StringBuilder outputBuilder = new StringBuilder(); 86 | 87 | String delimiter = "\t"; 88 | appendIfNotNull(outputBuilder, priorityStr, delimiter); 89 | appendIfNotNull(outputBuilder, tag, delimiter); 90 | appendIfNotNull(outputBuilder, msg, delimiter); 91 | appendIfNotNull(outputBuilder, exceptionStr, delimiter); 92 | 93 | // In case this was originally called from an AsyncTask or some other off-UI thread, 94 | // make sure the update occurs within the UI thread. 95 | ((Activity) getContext()).runOnUiThread( (new Thread(new Runnable() { 96 | @Override 97 | public void run() { 98 | // Display the text we just generated within the LogView. 99 | appendToLog(outputBuilder.toString()); 100 | } 101 | }))); 102 | 103 | if (mNext != null) { 104 | mNext.println(priority, tag, msg, tr); 105 | } 106 | } 107 | 108 | public LogNode getNext() { 109 | return mNext; 110 | } 111 | 112 | public void setNext(LogNode node) { 113 | mNext = node; 114 | } 115 | 116 | /** Takes a string and adds to it, with a separator, if the bit to be added isn't null. Since 117 | * the logger takes so many arguments that might be null, this method helps cut out some of the 118 | * agonizing tedium of writing the same 3 lines over and over. 119 | * @param source StringBuilder containing the text to append to. 120 | * @param addStr The String to append 121 | * @param delimiter The String to separate the source and appended strings. A tab or comma, 122 | * for instance. 123 | * @return The fully concatenated String as a StringBuilder 124 | */ 125 | private StringBuilder appendIfNotNull(StringBuilder source, String addStr, String delimiter) { 126 | if (addStr != null) { 127 | if (addStr.length() == 0) { 128 | delimiter = ""; 129 | } 130 | 131 | return source.append(addStr).append(delimiter); 132 | } 133 | return source; 134 | } 135 | 136 | // The next LogNode in the chain. 137 | LogNode mNext; 138 | 139 | /** Outputs the string as a new line of log data in the LogView. */ 140 | public void appendToLog(String s) { 141 | append("\n" + s); 142 | } 143 | 144 | 145 | } 146 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/LogWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.android.common.logger; 17 | 18 | import android.util.Log; 19 | 20 | /** 21 | * Helper class which wraps Android's native Log utility in the Logger interface. This way 22 | * normal DDMS output can be one of the many targets receiving and outputting logs simultaneously. 23 | */ 24 | public class LogWrapper implements LogNode { 25 | 26 | // For piping: The next node to receive Log data after this one has done its work. 27 | private LogNode mNext; 28 | 29 | /** 30 | * Returns the next LogNode in the linked list. 31 | */ 32 | public LogNode getNext() { 33 | return mNext; 34 | } 35 | 36 | /** 37 | * Sets the LogNode data will be sent to.. 38 | */ 39 | public void setNext(LogNode node) { 40 | mNext = node; 41 | } 42 | 43 | /** 44 | * Prints data out to the console using Android's native log mechanism. 45 | * @param priority Log level of the data being logged. Verbose, Error, etc. 46 | * @param tag Tag for for the log data. Can be used to organize log statements. 47 | * @param msg The actual message to be logged. The actual message to be logged. 48 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 49 | * to extract and print useful information. 50 | */ 51 | @Override 52 | public void println(int priority, String tag, String msg, Throwable tr) { 53 | // There actually are log methods that don't take a msg parameter. For now, 54 | // if that's the case, just convert null to the empty string and move on. 55 | String useMsg = msg; 56 | if (useMsg == null) { 57 | useMsg = ""; 58 | } 59 | 60 | // If an exeption was provided, convert that exception to a usable string and attach 61 | // it to the end of the msg method. 62 | if (tr != null) { 63 | msg += "\n" + Log.getStackTraceString(tr); 64 | } 65 | 66 | // This is functionally identical to Log.x(tag, useMsg); 67 | // For instance, if priority were Log.VERBOSE, this would be the same as Log.v(tag, useMsg) 68 | Log.println(priority, tag, useMsg); 69 | 70 | // If this isn't the last node in the chain, move things along. 71 | if (mNext != null) { 72 | mNext.println(priority, tag, msg, tr); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/MessageOnlyLogFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.android.common.logger; 17 | 18 | /** 19 | * Simple {@link LogNode} filter, removes everything except the message. 20 | * Useful for situations like on-screen log output where you don't want a lot of metadata displayed, 21 | * just easy-to-read message updates as they're happening. 22 | */ 23 | public class MessageOnlyLogFilter implements LogNode { 24 | 25 | LogNode mNext; 26 | 27 | /** 28 | * Takes the "next" LogNode as a parameter, to simplify chaining. 29 | * 30 | * @param next The next LogNode in the pipeline. 31 | */ 32 | public MessageOnlyLogFilter(LogNode next) { 33 | mNext = next; 34 | } 35 | 36 | public MessageOnlyLogFilter() { 37 | } 38 | 39 | @Override 40 | public void println(int priority, String tag, String msg, Throwable tr) { 41 | if (mNext != null) { 42 | getNext().println(Log.NONE, null, msg, null); 43 | } 44 | } 45 | 46 | /** 47 | * Returns the next LogNode in the chain. 48 | */ 49 | public LogNode getNext() { 50 | return mNext; 51 | } 52 | 53 | /** 54 | * Sets the LogNode data will be sent to.. 55 | */ 56 | public void setNext(LogNode node) { 57 | mNext = node; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Application/src/main/res/drawable-hdpi/ic_action_device_access_bluetooth_searching.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/res/drawable-hdpi/ic_action_device_access_bluetooth_searching.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-hdpi/tile.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/res/drawable-hdpi/tile.9.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-mdpi/ic_action_device_access_bluetooth_searching.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/res/drawable-mdpi/ic_action_device_access_bluetooth_searching.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-xhdpi/ic_action_device_access_bluetooth_searching.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/res/drawable-xhdpi/ic_action_device_access_bluetooth_searching.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-xxhdpi/ic_action_device_access_bluetooth_searching.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/res/drawable-xxhdpi/ic_action_device_access_bluetooth_searching.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atilag/BluetoothLEChat/90ccad9f11ac06d9a58451033c61bff30b08cd3e/Application/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /Application/src/main/res/layout-w720dp/activity_main.xml: -------------------------------------------------------------------------------- 1 | 16 | 22 | 23 | 29 | 30 | 34 | 35 | 44 | 45 | 46 | 50 | 51 | 57 | 58 | 59 | 60 | 64 | 65 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /Application/src/main/res/layout/activity_ble_advertising.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 17 | 18 | 26 | 27 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Application/src/main/res/layout/activity_ble_discovering.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 19 | 20 | 26 | 27 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Application/src/main/res/layout/activity_device_list.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 21 | 22 | 32 | 33 | 40 | 41 | 51 | 52 | 59 | 60 |