diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/android/shimmerService/ShimmerService.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/android/shimmerService/ShimmerService.java index d8cb1d90..5fda5af9 100644 --- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/android/shimmerService/ShimmerService.java +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/android/shimmerService/ShimmerService.java @@ -187,11 +187,29 @@ public void setECGtoHRSignal(String ecgtoHR){ public void onDestroy() { Toast.makeText(this, "Shimmer Service Stopped", Toast.LENGTH_LONG).show(); Log.d(TAG, "onDestroy"); - btManager.disconnectAllDevices(); + if (btManager != null) { + btManager.disconnectAllDevices(); + } + } + + /** + * btManager is null when Bluetooth was off as the service was created (onCreate logs "Bluetooth + * not Enabled"). Creates it if Bluetooth has been switched on since; an existing one is kept, so + * whatever holds it from getBluetoothManager() still matches the service. Call this rather than + * createNewBluetoothManager() once Bluetooth comes on. + * @return whether there is a BluetoothManager to use + */ + public boolean ensureBluetoothManager() { + if (btManager == null) { + createNewBluetoothManager(); + } + return btManager != null; } public void disconnectAllDevices(){ - btManager.disconnectAllDevices(); + if (btManager != null) { + btManager.disconnectAllDevices(); + } mMultiShimmer.clear(); mLogShimmer.clear(); } @@ -255,14 +273,17 @@ public boolean isECGtoHREnabled(){ } public void connectShimmer(final String bluetoothAddress,Context context){ + if (!ensureBluetoothManager()) return; btManager.connectShimmerThroughBTAddress(bluetoothAddress,"",context); } public void connectShimmer(final String bluetoothAddress,final String deviceName, Context context){ + if (!ensureBluetoothManager()) return; btManager.connectShimmerThroughBTAddress(bluetoothAddress,deviceName,context); } public void connectShimmer(final String bluetoothAddress,final String deviceName, ShimmerBluetoothManagerAndroid.BT_TYPE preferredBtType, Context context){ + if (!ensureBluetoothManager()) return; boolean isVerisense = false; if (deviceName!=null){ if (deviceName.contains(VerisenseDevice.VERISENSE_PREFIX)) { @@ -281,6 +302,7 @@ public void connectShimmer(final String bluetoothAddress,final String deviceName } public void connectShimmer(final String bluetoothAddress){ + if (!ensureBluetoothManager()) return; btManager.connectShimmerThroughBTAddress(bluetoothAddress); } @@ -288,7 +310,9 @@ public void onStop(){ Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show(); Log.d(TAG, "onDestroy"); - btManager.disconnectAllDevices(); + if (btManager != null) { + btManager.disconnectAllDevices(); + } } /** @@ -1201,7 +1225,7 @@ public int getShimmerVersion (String bluetoothAddress){ } public ShimmerDevice getShimmer(String bluetoothAddress){ - return btManager.getShimmer(bluetoothAddress); + return btManager == null ? null : btManager.getShimmer(bluetoothAddress); } public void test(){ @@ -1310,7 +1334,8 @@ public ShimmerBluetoothManagerAndroid getBluetoothManager() { } public List getListOfConnectedDevices() { - return btManager.getListOfConnectedDevices(); + // No BluetoothManager (Bluetooth was off when the service started) means no devices. + return btManager == null ? new ArrayList() : btManager.getListOfConnectedDevices(); } public void configureShimmer(ShimmerDevice device) { @@ -1330,6 +1355,7 @@ public void createNewBluetoothManager() { try { btManager = new ShimmerBluetoothManagerAndroid(this, mHandler); + Log.d(TAG, "Bluetooth Manager created"); } catch (Exception e) { Log.e(TAG, "ERROR! " + e); Toast.makeText(this, "Error! Could not create Bluetooth Manager!", Toast.LENGTH_LONG).show(); diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/android/shimmerService/AAPI_00008_ServiceWithoutBluetoothManagerTest.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/android/shimmerService/AAPI_00008_ServiceWithoutBluetoothManagerTest.java new file mode 100644 index 00000000..3eaccd3c --- /dev/null +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/android/shimmerService/AAPI_00008_ServiceWithoutBluetoothManagerTest.java @@ -0,0 +1,57 @@ +package com.shimmerresearch.android.shimmerService; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import com.shimmerresearch.driver.ShimmerDevice; + +/** + * DEV-1402: with Bluetooth off, ShimmerService.onCreate() cannot create its + * BluetoothManager ("Bluetooth not Enabled") and leaves btManager null. The + * ShimmerCapture options menu then called getListOfConnectedDevices() on it, and + * the app crashed at launch. Google Play's pre-launch test refused the 1.3.4 + * release for it. + *

+ * A missing BluetoothManager now means no devices: these calls return empty or + * null, or do nothing, instead of throwing. + *

+ * No hardware: a service that has not been through onCreate() has no + * BluetoothManager, which is the state Bluetooth being off leaves it in. + */ +public class AAPI_00008_ServiceWithoutBluetoothManagerTest { + + private static final String ADDRESS = "00:06:66:00:00:01"; + + private ShimmerService service; + + @Before + public void createServiceWithoutBluetoothManager() { + service = new ShimmerService(); + assertNull("precondition: no BluetoothManager", service.getBluetoothManager()); + } + + @Test + public void listOfConnectedDevicesIsEmpty() { + List devices = service.getListOfConnectedDevices(); + assertNotNull(devices); + assertTrue(devices.isEmpty()); + } + + @Test + public void getShimmerFindsNoDevice() { + assertNull(service.getShimmer(ADDRESS)); + } + + @Test + public void disconnectAllDevicesClearsTheServiceState() { + service.mMultiShimmer.put(ADDRESS, new Object()); + service.disconnectAllDevices(); + assertTrue(service.mMultiShimmer.isEmpty()); + } +} diff --git a/ShimmerAndroidInstrumentDriver/shimmerServiceExample/build.gradle b/ShimmerAndroidInstrumentDriver/shimmerServiceExample/build.gradle index 6634fde0..ddf660a7 100644 --- a/ShimmerAndroidInstrumentDriver/shimmerServiceExample/build.gradle +++ b/ShimmerAndroidInstrumentDriver/shimmerServiceExample/build.gradle @@ -8,7 +8,7 @@ android { applicationId "com.shimmersensing.shimmerconnect" minSdkVersion 21 targetSdkVersion 36 - versionCode 36 + versionCode 37 versionName "1.3.4" multiDexEnabled true diff --git a/ShimmerAndroidInstrumentDriver/shimmerServiceExample/src/main/java/com/shimmerresearch/shimmercapture/MainActivity.java b/ShimmerAndroidInstrumentDriver/shimmerServiceExample/src/main/java/com/shimmerresearch/shimmercapture/MainActivity.java index 4e091746..0ba4d5a8 100644 --- a/ShimmerAndroidInstrumentDriver/shimmerServiceExample/src/main/java/com/shimmerresearch/shimmercapture/MainActivity.java +++ b/ShimmerAndroidInstrumentDriver/shimmerServiceExample/src/main/java/com/shimmerresearch/shimmercapture/MainActivity.java @@ -37,6 +37,7 @@ import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AppCompatActivity; +import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Gravity; @@ -100,7 +101,9 @@ public class MainActivity extends AppCompatActivity implements ConnectedShimmers final static String LOG_TAG = "Shimmer"; final static String SERVICE_TAG = "ShimmerService"; + final static int REQUEST_ENABLE_BT = 1; final static int REQUEST_CONNECT_SHIMMER = 2; + final static int REQUEST_PERMISSIONS = 110; public static APP_RELEASE_TYPE appReleaseType = APP_RELEASE_TYPE.PUBLIC; public enum APP_RELEASE_TYPE{ INTERNAL, @@ -185,7 +188,7 @@ public void requestPermissions(){ } if (!permissionGranted) { // Should we show an explanation? - ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT,Manifest.permission.BLUETOOTH_SCAN,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION}, 110); + ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT,Manifest.permission.BLUETOOTH_SCAN,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS); } else { startServiceandBTManager(); @@ -274,8 +277,10 @@ public void onRequestPermissionsResult( @NonNull String[] permissions, @NonNull int[] grantResults ){ - int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT); - if (permissionCheck != PackageManager.PERMISSION_GRANTED) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + // Start the service whatever the answer, as requestPermissions() does when they are already + // granted. This used to start it only when BLUETOOTH_CONNECT was refused. + if (requestCode == REQUEST_PERMISSIONS) { startServiceandBTManager(); } } @@ -287,6 +292,27 @@ protected void startServiceandBTManager(){ getApplicationContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE); Log.d(LOG_TAG, "Shimmer Service started"); Toast.makeText(this, "Shimmer Service started", Toast.LENGTH_SHORT).show(); + requestBluetoothEnableIfOff(); + } + + /** + * Asks the user to switch Bluetooth on if it is off. The service then has no BluetoothManager + * (it logs "Bluetooth not Enabled"); onActivityResult creates one once Bluetooth is on. + * @return true if Bluetooth is off, whether or not it could be asked for + */ + private boolean requestBluetoothEnableIfOff() { + BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); + if (adapter == null || adapter.isEnabled()) { + return false; + } + // From Android 12 the enable request needs BLUETOOTH_CONNECT, or it throws. + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S + || ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) { + startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BT); + } else { + Toast.makeText(this, "Bluetooth is off. Turn it on to connect to a device.", Toast.LENGTH_LONG).show(); + } + return true; } @Override @@ -351,6 +377,9 @@ public boolean onOptionsItemSelected(MenuItem item) { final Toast otherTaskOngoingToast = Toast.makeText(this, "Please wait until current task is finished", Toast.LENGTH_LONG); int id = item.getItemId(); if(id == R.id.connect_device){ + if (requestBluetoothEnableIfOff()) { + return true; //Nothing to connect to until Bluetooth is on + } Intent pairedDevicesIntent = new Intent(getApplicationContext(), ShimmerBluetoothDialog.class); startActivityForResult(pairedDevicesIntent, REQUEST_CONNECT_SHIMMER); return true; @@ -720,18 +749,17 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { */ } } - if (requestCode == 1) { //The system Bluetooth enable dialog has returned a result + if (requestCode == REQUEST_ENABLE_BT) { //The system Bluetooth enable dialog has returned a result if (resultCode == RESULT_OK) { - Intent intent = new Intent(this, ShimmerService.class); - startService(intent); - getApplicationContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - Log.d(LOG_TAG, "Shimmer Service started"); - Toast.makeText(this, "Shimmer Service started", Toast.LENGTH_SHORT).show(); + //If Bluetooth was off when the service was created, it has no BluetoothManager yet. + //ensureBluetoothManager() keeps one it already has (Bluetooth was only switched off + //later), so nothing holding it is orphaned. If the service is not bound yet, + //connecting creates the manager instead. + if (mService != null) { + mService.ensureBluetoothManager(); + } } else if (resultCode == RESULT_CANCELED) { - Toast.makeText(this, "Please enable Bluetooth to proceed.", Toast.LENGTH_LONG).show(); - int REQUEST_ENABLE_BT = 1; - Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); - startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); + Toast.makeText(this, "Bluetooth is off. Turn it on to connect to a device.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Unknown Error! Your device may not support Bluetooth!", Toast.LENGTH_LONG).show(); }