├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── libs │ └── smartgattlib-1.3.jar ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── hypermatix │ │ └── com │ │ └── bluetoothqueue │ │ ├── BluetoothCommand.java │ │ ├── BluetoothQueueService.java │ │ ├── DelayCommand.java │ │ ├── DeviceFragment.java │ │ ├── DeviceScanCallback.java │ │ └── MainActivity.java │ └── res │ ├── layout │ ├── activity_main.xml │ └── fragment_device.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | *.iml 8 | /.idea 9 | /build 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | BluetoothQueue is a sample app for Android that demonstrates the idea of a queue system for BLE commands. 2 | 3 | 4 | Read more about it at blog post here: 5 | 6 | http://www.brendanwhelan.net/2015/bluetooth-command-queuing-for-android 7 | 8 | 9 | 10 | The app requires Android device with OS 4.3 or greater. 11 | 12 | The app also assumes the device you connect to has a standard Serial Number characteristic in a Device Information service. 13 | 14 | https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.device_information.xml -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 22 5 | buildToolsVersion "21.1.2" 6 | 7 | defaultConfig { 8 | applicationId "hypermatix.com.bluetoothqueue" 9 | minSdkVersion 18 10 | targetSdkVersion 22 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | compile 'com.android.support:appcompat-v7:22.0.0' 25 | } 26 | -------------------------------------------------------------------------------- /app/libs/smartgattlib-1.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freewheeling/BluetoothQueue/866b79b50b61606e0bc00376d68a39562af8eaf6/app/libs/smartgattlib-1.3.jar -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Programs\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 8 | 9 | 10 | 11 | 16 | 20 | 21 | 22 | 23 | 24 | 25 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /app/src/main/java/hypermatix/com/bluetoothqueue/BluetoothCommand.java: -------------------------------------------------------------------------------- 1 | package hypermatix.com.bluetoothqueue; 2 | 3 | import android.bluetooth.BluetoothGatt; 4 | 5 | import com.movisens.smartgattlib.Characteristic; 6 | 7 | //You could subclass this to implement different, custom, or more complex 8 | //types of bluetooth commands (e.g. a compound command involving multiple writes, etc.) 9 | public abstract class BluetoothCommand { 10 | public void execute(BluetoothGatt gatt){} 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/hypermatix/com/bluetoothqueue/BluetoothQueueService.java: -------------------------------------------------------------------------------- 1 | package hypermatix.com.bluetoothqueue; 2 | 3 | import android.app.Service; 4 | import android.bluetooth.BluetoothAdapter; 5 | import android.bluetooth.BluetoothGatt; 6 | import android.bluetooth.BluetoothGattCallback; 7 | import android.bluetooth.BluetoothGattCharacteristic; 8 | import android.bluetooth.BluetoothGattDescriptor; 9 | import android.bluetooth.BluetoothGattService; 10 | import android.bluetooth.BluetoothManager; 11 | import android.content.Context; 12 | import android.content.Intent; 13 | import android.os.Binder; 14 | import android.os.Handler; 15 | import android.os.IBinder; 16 | import android.util.Log; 17 | 18 | import com.movisens.smartgattlib.Characteristic; 19 | 20 | import java.util.LinkedList; 21 | import java.util.UUID; 22 | import java.util.concurrent.Executor; 23 | import java.util.concurrent.Executors; 24 | import java.util.concurrent.Semaphore; 25 | 26 | public class BluetoothQueueService extends Service { 27 | 28 | //Broadcast Intent Constants 29 | public final static String DEVICE_CONNECTED = "com.hypermatix.bluetooth.DEVICE_CONNECTED"; 30 | public final static String DEVICE_DISCONNECTED = "com.hypermatix.bluetooth.DEVICE_DISCONNECTED"; 31 | public final static String DEVICE_CHARACTERISTIC_READ = "com.hypermatix.bluetooth.DEVICE_CHARACTERISTIC_READ"; 32 | public final static String DEVICE_QUEUE_STATS = "com.hypermatix.bluetooth.DEVICE_QUEUE_STATS"; 33 | public final static String EXTRA_VALUE = "com.hypermatix.bluetooth.EXTRA_VALUE"; 34 | 35 | Handler mHandler = new Handler(); 36 | DeviceScanCallback mScanCallback; 37 | BluetoothAdapter mBluetoothAdapter; 38 | BluetoothGatt mBluetoothGatt; 39 | LinkedList mCommandQueue = new LinkedList(); 40 | //Command Operation executor - will only run one at a time 41 | Executor mCommandExecutor = Executors.newSingleThreadExecutor(); 42 | //Semaphore lock to coordinate command executions, to ensure only one is 43 | //currently started and waiting on a response. 44 | Semaphore mCommandLock = new Semaphore(1,true); 45 | 46 | private final IBinder mBluetoothQueueServiceLocalBinder = new BluetoothQueueServiceLocalBinder(); 47 | 48 | @Override 49 | public IBinder onBind(Intent intent) { 50 | initialize(); 51 | return mBluetoothQueueServiceLocalBinder; //Locally-bound only 52 | } 53 | 54 | public class BluetoothQueueServiceLocalBinder extends Binder { 55 | BluetoothQueueService getService() { 56 | return BluetoothQueueService.this; 57 | } 58 | } 59 | 60 | private void initialize(){ 61 | if(mBluetoothAdapter == null){ 62 | //Initialize Bluetooth 63 | BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 64 | mBluetoothAdapter = bluetoothManager.getAdapter(); 65 | } 66 | } 67 | 68 | @Override 69 | public void onDestroy(){ 70 | disconnect(); 71 | if(mBluetoothGatt != null) mBluetoothGatt.close(); 72 | super.onDestroy(); 73 | } 74 | 75 | 76 | //Function to scan for advertising BLE devices to connect to 77 | public boolean scanForDevices(boolean on){ 78 | if(on){ 79 | //Turn scanning on 80 | if(!isScanningDevices()){ 81 | mScanCallback = new DeviceScanCallback(this); 82 | //Look for Devices with a standard DEVICE_INFORMATION service 83 | mBluetoothAdapter.startLeScan(new UUID[] {com.movisens.smartgattlib.Service.DEVICE_INFORMATION}, 84 | mScanCallback); 85 | //Ensure we won't Scan forever (save battery) 86 | mHandler.postDelayed(new Runnable() { 87 | @Override 88 | public void run() { 89 | if(isScanningDevices()) 90 | scanForDevices(false); 91 | } 92 | }, 30000); 93 | 94 | } 95 | }else{ 96 | //Turn scanning off 97 | if(isScanningDevices()){ 98 | mBluetoothAdapter.stopLeScan(mScanCallback); 99 | mScanCallback = null; 100 | } 101 | } 102 | return true; 103 | } 104 | 105 | public boolean isScanningDevices(){ 106 | return mScanCallback != null; 107 | } 108 | 109 | public void connect(String address){ 110 | mBluetoothGatt = mBluetoothAdapter.getRemoteDevice(address).connectGatt(this,false,mGattCallback); 111 | } 112 | 113 | public void disconnect(){ 114 | if(isConnected()) mBluetoothGatt.disconnect(); 115 | } 116 | 117 | public boolean isConnected(){ 118 | return mBluetoothGatt != null; 119 | } 120 | 121 | public void queueCommand(BluetoothCommand command){ 122 | synchronized (mCommandQueue) { 123 | mCommandQueue.add(command); //Add to end of stack 124 | sendBroadcast(DEVICE_QUEUE_STATS, 125 | String.format("Commands in queue: %d",mCommandQueue.size())); 126 | //Schedule a new runnable to process that command (one command at a time executed only) 127 | ExecuteCommandRunnable runnable = new ExecuteCommandRunnable(command); 128 | mCommandExecutor.execute(runnable); 129 | } 130 | } 131 | 132 | //Remove the current command from the queue, and release the lock 133 | //signalling the next queued command (if any) that it can start 134 | protected void dequeueCommand(){ 135 | mCommandQueue.pop(); 136 | sendBroadcast(DEVICE_QUEUE_STATS, 137 | String.format("Commands in queue: %d",mCommandQueue.size())); 138 | mCommandLock.release(); 139 | } 140 | 141 | private void sendBroadcast(String intentAction){ 142 | sendBroadcast(new Intent(intentAction)); 143 | } 144 | 145 | private void sendBroadcast(String intentAction, String value){ 146 | Intent intent = new Intent(intentAction); 147 | intent.putExtra(EXTRA_VALUE,value); 148 | sendBroadcast(intent); 149 | } 150 | 151 | //Runnable to execute a command from the queue 152 | class ExecuteCommandRunnable implements Runnable{ 153 | 154 | BluetoothCommand mCommand; 155 | 156 | public ExecuteCommandRunnable(BluetoothCommand command) { 157 | mCommand = command; 158 | } 159 | 160 | @Override 161 | public void run() { 162 | //Acquire semaphore lock to ensure no other operations can run until this one completed 163 | mCommandLock.acquireUninterruptibly(); 164 | //Tell the command to start itself. 165 | mCommand.execute(mBluetoothGatt); 166 | } 167 | }; 168 | 169 | 170 | //The main callback to handle bluetooth gatt client notifications 171 | private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { 172 | @Override 173 | public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { 174 | super.onConnectionStateChange(gatt, status, newState); 175 | if(newState == BluetoothGatt.STATE_CONNECTED){ 176 | if(status == BluetoothGatt.GATT_SUCCESS) { 177 | mBluetoothGatt.discoverServices(); 178 | }else{ 179 | mBluetoothGatt.close(); 180 | mBluetoothGatt = null; 181 | } 182 | } 183 | if(newState == BluetoothGatt.STATE_DISCONNECTED){ 184 | mBluetoothGatt.close(); 185 | mBluetoothGatt = null; 186 | sendBroadcast(DEVICE_DISCONNECTED); 187 | } 188 | } 189 | 190 | @Override 191 | public void onServicesDiscovered(BluetoothGatt gatt, int status) { 192 | super.onServicesDiscovered(gatt, status); 193 | sendBroadcast(DEVICE_CONNECTED); 194 | } 195 | 196 | @Override 197 | public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { 198 | super.onCharacteristicRead(gatt, characteristic, status); 199 | if(characteristic.getUuid().equals(Characteristic.SERIAL_NUMBER_STRING)){ 200 | sendBroadcast(DEVICE_CHARACTERISTIC_READ,characteristic.getStringValue(0)); 201 | dequeueCommand(); 202 | } 203 | } 204 | 205 | @Override 206 | public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { 207 | super.onCharacteristicChanged(gatt, characteristic); 208 | } 209 | 210 | @Override 211 | public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { 212 | super.onCharacteristicWrite(gatt, characteristic, status); 213 | } 214 | }; 215 | } 216 | -------------------------------------------------------------------------------- /app/src/main/java/hypermatix/com/bluetoothqueue/DelayCommand.java: -------------------------------------------------------------------------------- 1 | package hypermatix.com.bluetoothqueue; 2 | 3 | import android.bluetooth.BluetoothGatt; 4 | 5 | import com.movisens.smartgattlib.Characteristic; 6 | 7 | public class DelayCommand extends BluetoothCommand { 8 | public void execute(BluetoothGatt gatt){ 9 | try { 10 | synchronized (Thread.currentThread()) { 11 | Thread.currentThread().wait(500); 12 | } 13 | }catch(InterruptedException e){ 14 | //ignore 15 | } 16 | 17 | //As an example, read from serial number characteristic 18 | gatt.readCharacteristic( 19 | gatt.getService(com.movisens.smartgattlib.Service.DEVICE_INFORMATION) 20 | .getCharacteristic(Characteristic.SERIAL_NUMBER_STRING)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /app/src/main/java/hypermatix/com/bluetoothqueue/DeviceFragment.java: -------------------------------------------------------------------------------- 1 | package hypermatix.com.bluetoothqueue; 2 | 3 | import android.app.Activity; 4 | import android.app.AlertDialog; 5 | import android.app.Dialog; 6 | import android.app.DialogFragment; 7 | import android.content.BroadcastReceiver; 8 | import android.content.Context; 9 | import android.content.DialogInterface; 10 | import android.content.Intent; 11 | import android.content.IntentFilter; 12 | import android.os.Bundle; 13 | import android.view.LayoutInflater; 14 | import android.view.View; 15 | import android.view.ViewGroup; 16 | import android.widget.AdapterView; 17 | import android.widget.BaseAdapter; 18 | import android.widget.ListView; 19 | import android.widget.TextView; 20 | 21 | import java.util.ArrayList; 22 | import java.util.HashMap; 23 | 24 | public class DeviceFragment extends DialogFragment 25 | { 26 | public final static String TAG = DeviceFragment.class.getSimpleName(); 27 | 28 | private static AlertDialog.Builder builder; 29 | DeviceAdapter mDeviceAdapter; 30 | OnDeviceSelectListener mDeviceSelectListener; 31 | 32 | private final BroadcastReceiver mDeviceScanReceiver = new BroadcastReceiver() { 33 | @Override 34 | public void onReceive(Context context, Intent intent) { 35 | String address = intent.getStringExtra(DeviceScanCallback.EXTRA_ADDRESS); 36 | String name = intent.getStringExtra(DeviceScanCallback.EXTRA_NAME); 37 | mDeviceAdapter.addDevice(address,name); 38 | } 39 | }; 40 | 41 | public interface OnDeviceSelectListener{ 42 | void onDeviceSelect(String address); 43 | } 44 | 45 | public DeviceFragment(){} 46 | 47 | @Override 48 | public void onCreate(Bundle savedInstanceState) 49 | { 50 | super.onCreate(savedInstanceState); 51 | } 52 | 53 | @Override 54 | public void onResume() 55 | { 56 | //Register to receive device scan results 57 | IntentFilter intentFilter = new IntentFilter(); 58 | intentFilter.addAction(DeviceScanCallback.DEVICE_SCAN_RESULT); 59 | getActivity().registerReceiver(mDeviceScanReceiver,intentFilter); 60 | super.onResume(); 61 | } 62 | 63 | @Override 64 | public void onPause() 65 | { 66 | getActivity().unregisterReceiver(mDeviceScanReceiver); 67 | super.onPause(); 68 | } 69 | 70 | @Override 71 | public void onAttach(Activity activity){ 72 | super.onAttach(activity); 73 | mDeviceSelectListener = (OnDeviceSelectListener)activity; 74 | } 75 | 76 | @Override 77 | public Dialog onCreateDialog(Bundle savedInstanceState) 78 | { 79 | // Initializes list view adapter. 80 | mDeviceAdapter = new DeviceAdapter(); 81 | 82 | builder = new AlertDialog.Builder(getActivity()); 83 | builder.setTitle(R.string.select_device); 84 | LayoutInflater inflater = getActivity().getLayoutInflater(); 85 | View content = inflater.inflate(R.layout.fragment_device, null, false); 86 | ListView deviceList = (ListView) content.findViewById(R.id.list); 87 | deviceList.setAdapter(mDeviceAdapter); 88 | deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() 89 | { 90 | public void onItemClick(AdapterView parent, View view, int position, long id) 91 | { 92 | if(mDeviceSelectListener != null) 93 | mDeviceSelectListener.onDeviceSelect((String)view.getTag()); 94 | getDialog().dismiss(); 95 | } 96 | }); 97 | 98 | builder.setView(deviceList); 99 | builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() 100 | { 101 | public void onClick(DialogInterface dialog, int whichButton) 102 | { 103 | //Standard dismiss 104 | } 105 | }); 106 | return builder.create(); 107 | } 108 | 109 | private class DeviceAdapter extends BaseAdapter 110 | { 111 | private ArrayList mDeviceAddress = new ArrayList(); 112 | private ArrayList mDeviceName = new ArrayList(); 113 | private LayoutInflater mInflator; 114 | 115 | public DeviceAdapter() 116 | { 117 | super(); 118 | mInflator = getActivity().getLayoutInflater(); 119 | } 120 | 121 | public void addDevice(String address, String name) 122 | { 123 | if(!mDeviceAddress.contains(address)) 124 | { 125 | mDeviceAddress.add(address); 126 | mDeviceName.add(name); 127 | notifyDataSetChanged(); 128 | } 129 | } 130 | 131 | @Override 132 | public int getCount() 133 | { 134 | return mDeviceAddress.size(); 135 | } 136 | 137 | @Override 138 | public Object getItem(int i) 139 | { 140 | return mDeviceAddress.get(i); 141 | } 142 | 143 | @Override 144 | public long getItemId(int i) 145 | { 146 | return i; 147 | } 148 | 149 | @Override 150 | public View getView(int i, View view, ViewGroup viewGroup) 151 | { 152 | if(view == null) 153 | { 154 | view = mInflator.inflate(android.R.layout.simple_list_item_1, null); 155 | } 156 | 157 | String address = mDeviceAddress.get(i); 158 | String name = mDeviceName.get(i); 159 | ((TextView)view.findViewById(android.R.id.text1)).setText(name); 160 | view.setTag(address); 161 | 162 | return view; 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /app/src/main/java/hypermatix/com/bluetoothqueue/DeviceScanCallback.java: -------------------------------------------------------------------------------- 1 | package hypermatix.com.bluetoothqueue; 2 | 3 | import android.bluetooth.BluetoothAdapter; 4 | import android.bluetooth.BluetoothDevice; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | 8 | import java.util.ArrayList; 9 | 10 | public class DeviceScanCallback implements BluetoothAdapter.LeScanCallback { 11 | 12 | //Broadcast Intent Constants 13 | public final static String DEVICE_SCAN_RESULT = "com.hypermatix.bluetooth.DEVICE_SCAN_RESULT"; 14 | public final static String EXTRA_ADDRESS = "com.hypermatix.bluetooth.EXTRA_ADDRESS"; 15 | public final static String EXTRA_NAME = "com.hypermatix.bluetooth.EXTRA_NAME"; 16 | 17 | ArrayList mDiscoveredDevices = new ArrayList(); 18 | Context mContext; 19 | 20 | public DeviceScanCallback(Context context){ 21 | mContext = context; 22 | } 23 | 24 | @Override 25 | public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) 26 | { 27 | if(!mDiscoveredDevices.contains(device.getAddress())) { 28 | mDiscoveredDevices.add(device.getAddress()); 29 | //Send a broadcast to main part of the app to alert it to new found device 30 | Intent broadcast = new Intent(DEVICE_SCAN_RESULT); 31 | broadcast.putExtra(EXTRA_ADDRESS, device.getAddress()); 32 | broadcast.putExtra(EXTRA_NAME, device.getName()); 33 | mContext.sendBroadcast(broadcast); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /app/src/main/java/hypermatix/com/bluetoothqueue/MainActivity.java: -------------------------------------------------------------------------------- 1 | package hypermatix.com.bluetoothqueue; 2 | 3 | import android.app.DialogFragment; 4 | import android.app.Fragment; 5 | import android.content.BroadcastReceiver; 6 | import android.content.ComponentName; 7 | import android.content.Context; 8 | import android.content.Intent; 9 | import android.content.IntentFilter; 10 | import android.content.ServiceConnection; 11 | import android.os.IBinder; 12 | import android.support.v7.app.ActionBarActivity; 13 | import android.os.Bundle; 14 | import android.view.View; 15 | import android.widget.Button; 16 | import android.widget.TextView; 17 | 18 | 19 | public class MainActivity extends ActionBarActivity 20 | implements DeviceFragment.OnDeviceSelectListener{ 21 | 22 | Button mButtonConnect, mButtonSendCommand; 23 | TextView mTextResult, mTextStats; 24 | BluetoothQueueService mBluetoothService; 25 | boolean mIsBound = false; 26 | 27 | private final BroadcastReceiver mServiceReceiver = new BroadcastReceiver() { 28 | @Override 29 | public void onReceive(Context context, Intent intent) { 30 | String action = intent.getAction(); 31 | if(action == BluetoothQueueService.DEVICE_CONNECTED){ 32 | mButtonConnect.setText(R.string.disconnect_device); 33 | mButtonSendCommand.setEnabled(true); 34 | } 35 | if(action == BluetoothQueueService.DEVICE_DISCONNECTED){ 36 | mButtonConnect.setText(R.string.connect_device); 37 | mButtonSendCommand.setEnabled(false); 38 | mTextResult.setText(null); 39 | mTextStats.setText(null); 40 | } 41 | if(action == BluetoothQueueService.DEVICE_CHARACTERISTIC_READ){ 42 | mTextResult.setText( 43 | String.format("Serial No.: %s",intent.getStringExtra(BluetoothQueueService.EXTRA_VALUE))); 44 | } 45 | if(action == BluetoothQueueService.DEVICE_QUEUE_STATS){ 46 | mTextStats.setText(intent.getStringExtra(BluetoothQueueService.EXTRA_VALUE)); 47 | } 48 | } 49 | }; 50 | 51 | private ServiceConnection mServiceConnection = new ServiceConnection() { 52 | public void onServiceConnected(ComponentName className, 53 | IBinder service) { 54 | BluetoothQueueService.BluetoothQueueServiceLocalBinder binder = 55 | (BluetoothQueueService.BluetoothQueueServiceLocalBinder) service; 56 | mBluetoothService = binder.getService(); 57 | mIsBound = true; 58 | registerServiceReceiver(); 59 | } 60 | 61 | public void onServiceDisconnected(ComponentName arg0) { 62 | mIsBound = false; 63 | unregisterServiceReceiver(); 64 | } 65 | }; 66 | 67 | private void registerServiceReceiver(){ 68 | IntentFilter intentFilter = new IntentFilter(); 69 | intentFilter.addAction(BluetoothQueueService.DEVICE_CONNECTED); 70 | intentFilter.addAction(BluetoothQueueService.DEVICE_DISCONNECTED); 71 | intentFilter.addAction(BluetoothQueueService.DEVICE_CHARACTERISTIC_READ); 72 | intentFilter.addAction(BluetoothQueueService.DEVICE_QUEUE_STATS); 73 | registerReceiver(mServiceReceiver,intentFilter); 74 | } 75 | 76 | private void unregisterServiceReceiver(){ 77 | unregisterReceiver(mServiceReceiver); 78 | } 79 | 80 | @Override 81 | protected void onCreate(Bundle savedInstanceState) { 82 | super.onCreate(savedInstanceState); 83 | setContentView(R.layout.activity_main); 84 | Intent intent = new Intent(this, BluetoothQueueService.class); 85 | bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); 86 | mButtonConnect = (Button)findViewById(R.id.button_connect); 87 | mButtonSendCommand = (Button)findViewById(R.id.button_send); 88 | mButtonConnect.setOnClickListener(new View.OnClickListener() { 89 | @Override 90 | public void onClick(View view) { 91 | toggleConnect(); 92 | } 93 | }); 94 | mButtonSendCommand.setOnClickListener(new View.OnClickListener() { 95 | @Override 96 | public void onClick(View v) { 97 | sendQueuedCommand(); 98 | } 99 | }); 100 | mTextResult = (TextView)findViewById(R.id.text_result); 101 | mTextStats = (TextView)findViewById(R.id.text_stats); 102 | } 103 | 104 | private void toggleConnect(){ 105 | if(mIsBound){ 106 | if(mBluetoothService.isConnected()){ 107 | mBluetoothService.disconnect(); 108 | }else { 109 | //Select device to connect to 110 | DeviceFragment fragment = (DeviceFragment) Fragment.instantiate(this, DeviceFragment.class.getName()); 111 | fragment.show(getFragmentManager(), DeviceFragment.TAG); 112 | mBluetoothService.scanForDevices(true); 113 | } 114 | } 115 | } 116 | 117 | private void sendQueuedCommand(){ 118 | if(mIsBound){ 119 | //Use a sample command with a delay in it to demonstarte 120 | BluetoothCommand command = new DelayCommand(); 121 | mBluetoothService.queueCommand(command); 122 | } 123 | } 124 | 125 | //OnDeviceSelectListener 126 | public void onDeviceSelect(String address){ 127 | if(mIsBound) mBluetoothService.connect(address); 128 | } 129 | } -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 12 |