Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down Expand Up @@ -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)) {
Expand All @@ -281,14 +302,17 @@ public void connectShimmer(final String bluetoothAddress,final String deviceName
}

public void connectShimmer(final String bluetoothAddress){
if (!ensureBluetoothManager()) return;
btManager.connectShimmerThroughBTAddress(bluetoothAddress);
}

public void onStop(){
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");

btManager.disconnectAllDevices();
if (btManager != null) {
btManager.disconnectAllDevices();
}
}

/**
Expand Down Expand Up @@ -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(){
Expand Down Expand Up @@ -1310,7 +1334,8 @@ public ShimmerBluetoothManagerAndroid getBluetoothManager() {
}

public List<ShimmerDevice> getListOfConnectedDevices() {
return btManager.getListOfConnectedDevices();
// No BluetoothManager (Bluetooth was off when the service started) means no devices.
return btManager == null ? new ArrayList<ShimmerDevice>() : btManager.getListOfConnectedDevices();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The guard covers only some of btManager's uses. This PR guards about six of the ~60 btManager. calls in ShimmerService: the ones the Play crash and the tested menus reached. Still unguarded:

  • the public onStop() (L307), which calls btManager.disconnectAllDevices() just as onDestroy() did;
  • getBluetoothManager() (L1328), which returns null to callers that dereference it straight away: SignalsToPlotFragment (both copies), both PlotFragments, and MainActivity L598/923/975;
  • every other btManager. call: startStreamingAllDevices(), setAllEnabledSensors(), the write*/get* methods.

ShimmerService is library code, and the PR notes say the other apps using it get the guard too. But an app that reaches any of these with Bluetooth off still gets the same NullPointerException. Guarding it once would cover all of them: route every method through one accessor (ensureBluetoothManager(), returning early or throwing a clear exception when it's false), or use a null-object manager. If that's too much for this release, a follow-up issue would keep it from being lost.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on the gap. In 247271a I guarded onStop() like onDestroy(). I left the rest for a follow-up ticket, for this reason. Within ShimmerCapture, every other btManager/getBluetoothManager() call you list runs only for a connected or selected device: configure, the sensor/config lists, plot and signals-to-plot while streaming. A device can't connect until a manager exists, and the manager is only ever missing when Bluetooth was off at start, until Allow creates it. So the app can't reach them with null. Other apps on ShimmerService can, so I'll raise a follow-up to route every use through one accessor, with a clear failure instead of an NPE, and link it here.

}

public void configureShimmer(ShimmerDevice device) {
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* A missing BluetoothManager now means no devices: these calls return empty or
* null, or do nothing, instead of throwing.
* <p>
* 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<ShimmerDevice> 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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ android {
applicationId "com.shimmersensing.shimmerconnect"
minSdkVersion 21
targetSdkVersion 36
versionCode 36
versionCode 37
versionName "1.3.4"
multiDexEnabled true

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
}
}
Expand All @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}
Expand Down
Loading