From ef11372ee03e74c9448b0df8e5a61448ce89b413 Mon Sep 17 00:00:00 2001 From: Erik Johansson Date: Fri, 13 Apr 2018 00:47:25 +0200 Subject: [PATCH] Connect directly to the bluetooth device found in scan Instead of always performing a scan before connecting, use the address stored in the scan to connect directly to the scale. This also means that the location is permission is only needed during the scan and can be revoked afterwards. --- .../com/health/openscale/core/OpenScale.java | 38 ++--- .../bluetooth/BluetoothCommunication.java | 132 ++++++------------ .../bluetooth/BluetoothCustomOpenScale.java | 14 +- .../core/bluetooth/BluetoothIhealthHS3.java | 17 +-- .../health/openscale/gui/MainActivity.java | 85 +++++------ .../gui/preferences/BluetoothPreferences.java | 4 +- .../openscale/gui/utils/PermissionHelper.java | 26 ++-- .../app/src/main/res/values/strings.xml | 2 +- 8 files changed, 120 insertions(+), 198 deletions(-) diff --git a/android_app/app/src/main/java/com/health/openscale/core/OpenScale.java b/android_app/app/src/main/java/com/health/openscale/core/OpenScale.java index b20b66d6..9ba781a0 100644 --- a/android_app/app/src/main/java/com/health/openscale/core/OpenScale.java +++ b/android_app/app/src/main/java/com/health/openscale/core/OpenScale.java @@ -78,8 +78,7 @@ public class OpenScale { private ScaleUser selectedScaleUser; private List scaleMeasurementList; - private BluetoothCommunication btCom; - private String btDeviceName; + private BluetoothCommunication btDeviceDriver; private AlarmHandler alarmHandler; private Context context; @@ -89,7 +88,7 @@ public class OpenScale { private OpenScale(Context context) { this.context = context; alarmHandler = new AlarmHandler(); - btCom = null; + btDeviceDriver = null; fragmentList = new ArrayList<>(); reopenDatabase(); @@ -472,30 +471,33 @@ public class OpenScale { return measurementDAO.getAllInRange(startCalender.getTime(), endCalender.getTime(), selectedUserId); } - public boolean startSearchingForBluetooth(String deviceName, Handler callbackBtHandler) { - Log.d("OpenScale", "Bluetooth Server started! I am searching for device ..."); + public boolean connectToBluetoothDevice(String deviceName, String hwAddress, Handler callbackBtHandler) { + Log.d("OpenScale", "Trying to connect to bluetooth device " + hwAddress + + " (" + deviceName + ")"); - btCom = BluetoothFactory.createDeviceDriver(context, deviceName); - if (btCom == null) { + disconnectFromBluetoothDevice(); + + btDeviceDriver = BluetoothFactory.createDeviceDriver(context, deviceName); + if (btDeviceDriver == null) { return false; } - btCom.registerCallbackHandler(callbackBtHandler); - btDeviceName = deviceName; - - btCom.startSearching(btDeviceName); + btDeviceDriver.registerCallbackHandler(callbackBtHandler); + btDeviceDriver.connect(hwAddress); return true; } - public boolean stopSearchingForBluetooth() { - if (btCom != null) { - btCom.stopSearching(); - btCom = null; - Log.d("OpenScale", "Bluetooth Server explicit stopped!"); - return true; + public boolean disconnectFromBluetoothDevice() { + if (btDeviceDriver == null) { + return false; } - return false; + + Log.d("OpenScale", "Disconnecting from bluetooth device"); + btDeviceDriver.disconnect(true); + btDeviceDriver = null; + + return true; } public void registerFragment(FragmentUpdateListener fragment) { diff --git a/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothCommunication.java b/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothCommunication.java index ceb82a5e..a20d03eb 100644 --- a/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothCommunication.java +++ b/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothCommunication.java @@ -23,10 +23,7 @@ import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothProfile; -import android.content.BroadcastReceiver; import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; import android.os.Handler; import android.util.Log; @@ -46,12 +43,10 @@ public abstract class BluetoothCommunication { protected Context context; private Handler callbackBtHandler; - private static BluetoothGatt bluetoothGatt; + private BluetoothGatt bluetoothGatt; + private boolean connectionEstablished; protected BluetoothGattCallback gattCallback; protected BluetoothAdapter btAdapter; - private Handler searchHandler; - private String btDeviceName; - public boolean isReceiverRegistered; private int cmdStepNr; private int initStepNr; @@ -66,10 +61,9 @@ public abstract class BluetoothCommunication { { this.context = context; btAdapter = BluetoothAdapter.getDefaultAdapter(); - searchHandler = new Handler(); gattCallback = new GattCallback(); - isReceiverRegistered = false; bluetoothGatt = null; + connectionEstablished = false; } /** @@ -328,86 +322,36 @@ public abstract class BluetoothCommunication { } /** - * Start searching for a Bluetooth device. - * - * @note the hardware address is checked. Bluetooth device address has to be start with one of hwAddresses(). + * Connect to a Bluetooth device. * * On successfully connection Bluetooth machine state is automatically triggered. - * If no device was found the search process is automatically stopped. + * If the device is not found the process is automatically stopped. * - * @param deviceName the Bluetooth device name that is compared to the found devices. + * @param hwAddress the Bluetooth address to connect to */ - public void startSearching(String deviceName) { - btDeviceName = deviceName; + public void connect(String hwAddress) { + btAdapter.cancelDiscovery(); - IntentFilter filter = new IntentFilter(); - - filter.addAction(BluetoothDevice.ACTION_FOUND); - filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); - - if (isReceiverRegistered == false) { - context.registerReceiver(mReceiver, filter); - isReceiverRegistered = true; - btAdapter.startDiscovery(); - } else { - try { - context.unregisterReceiver(mReceiver); - isReceiverRegistered = false; - } catch (Exception e) { - isReceiverRegistered = false; - } - startSearching(deviceName); - } + BluetoothDevice device = btAdapter.getRemoteDevice(hwAddress); + bluetoothGatt = device.connectGatt(context, false, gattCallback); } - private final BroadcastReceiver mReceiver = new BroadcastReceiver() { - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - - if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { - //discovery finishes, dismis progress dialog - if (bluetoothGatt == null) { - setBtStatus(BT_STATUS_CODE.BT_NO_DEVICE_FOUND); - } - } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { - //bluetooth device found - BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); - - if (device.getName() == null) { - return; - } - - if (device.getName().toLowerCase().equals(btDeviceName.toLowerCase())) { - Log.d("BluetoothCommunication", btDeviceName + " found trying to connect..."); - - bluetoothGatt = device.connectGatt(context, true, gattCallback); - } - } - } - }; - /** - * Stop searching for a Bluetooth device + * Disconnect from a Bluetooth device */ - public void stopSearching() { - if (bluetoothGatt != null) - { - bluetoothGatt.disconnect(); - bluetoothGatt.close(); - bluetoothGatt = null; + public void disconnect(boolean doCleanup) { + if (bluetoothGatt == null) { + return; } - if (isReceiverRegistered == true) { - try { - context.unregisterReceiver(mReceiver); - isReceiverRegistered = false; - } catch (Exception e) { - isReceiverRegistered = false; - } + if (btMachineState != BT_MACHINE_STATE.BT_CLEANUP_STATE && doCleanup) { + setBtMachineState(BT_MACHINE_STATE.BT_CLEANUP_STATE); + nextMachineStateStep(); } - searchHandler.removeCallbacksAndMessages(null); - btAdapter.cancelDiscovery(); + bluetoothGatt.disconnect(); + bluetoothGatt.close(); + bluetoothGatt = null; } /** @@ -439,14 +383,16 @@ public abstract class BluetoothCommunication { private void handleRequests() { synchronized (openRequest) { // check for pending request - if (openRequest) + if (openRequest) { return; // yes, do nothing + } // handle descriptor requests first BluetoothGattDescriptor descriptorRequest = descriptorRequestQueue.poll(); if (descriptorRequest != null) { - if (!bluetoothGatt.writeDescriptor(descriptorRequest)) + if (!bluetoothGatt.writeDescriptor(descriptorRequest)) { Log.d("BTC", "Descriptor Write failed(" + byteInHex(descriptorRequest.getValue()) + ")"); + } openRequest = true; return; } @@ -454,8 +400,9 @@ public abstract class BluetoothCommunication { // handle characteristics requests second BluetoothGattCharacteristic characteristicRequest = characteristicRequestQueue.poll(); if (characteristicRequest != null) { - if (!bluetoothGatt.writeCharacteristic(characteristicRequest)) + if (!bluetoothGatt.writeCharacteristic(characteristicRequest)) { Log.d("BTC", "Characteristic Write failed(" + byteInHex(characteristicRequest.getValue()) + ")"); + } openRequest = true; return; } @@ -472,11 +419,15 @@ public abstract class BluetoothCommunication { @Override public void onConnectionStateChange(final BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { + connectionEstablished = true; setBtStatus(BT_STATUS_CODE.BT_CONNECTION_ESTABLISHED); gatt.discoverServices(); - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { - setBtStatus(BT_STATUS_CODE.BT_CONNECTION_LOST); - stopSearching(); + } + else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + setBtStatus(connectionEstablished + ? BT_STATUS_CODE.BT_CONNECTION_LOST + : BT_STATUS_CODE.BT_NO_DEVICE_FOUND); + disconnect(false); } } @@ -501,8 +452,8 @@ public abstract class BluetoothCommunication { // Empty } - btMachineState = BT_MACHINE_STATE.BT_INIT_STATE; - nextMachineStateStep(); + // Start the state machine + setBtMachineState(BT_MACHINE_STATE.BT_INIT_STATE); } @Override @@ -516,9 +467,9 @@ public abstract class BluetoothCommunication { } @Override - public void onCharacteristicWrite (BluetoothGatt gatt, - BluetoothGattCharacteristic characteristic, - int status) { + public void onCharacteristicWrite(BluetoothGatt gatt, + BluetoothGattCharacteristic characteristic, + int status) { synchronized (openRequest) { openRequest = false; handleRequests(); @@ -526,9 +477,9 @@ public abstract class BluetoothCommunication { } @Override - public void onCharacteristicRead (BluetoothGatt gatt, - BluetoothGattCharacteristic characteristic, - int status) { + public void onCharacteristicRead(BluetoothGatt gatt, + BluetoothGattCharacteristic characteristic, + int status) { onBluetoothDataRead(gatt, characteristic, status); synchronized (openRequest) { openRequest = false; @@ -543,4 +494,3 @@ public abstract class BluetoothCommunication { } } } - diff --git a/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothCustomOpenScale.java b/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothCustomOpenScale.java index 71164af8..adad451e 100644 --- a/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothCustomOpenScale.java +++ b/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothCustomOpenScale.java @@ -27,7 +27,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.Set; import java.util.UUID; public class BluetoothCustomOpenScale extends BluetoothCommunication { @@ -63,18 +62,15 @@ public class BluetoothCustomOpenScale extends BluetoothCommunication { } @Override - public void startSearching(String deviceName) { + public void connect(String hwAddress) { if (btAdapter == null) { setBtStatus(BT_STATUS_CODE.BT_NO_DEVICE_FOUND); return; } - Set pairedDevices = btAdapter.getBondedDevices(); - - for (BluetoothDevice device : pairedDevices) { - // check if we can found bluetooth device name in the pairing list - if (device != null && device.getName().equals(deviceName)) { + for (BluetoothDevice device : btAdapter.getBondedDevices()) { + if (device != null && device.getAddress().equals(hwAddress)) { btDevice = device; try { @@ -101,7 +97,7 @@ public class BluetoothCustomOpenScale extends BluetoothCommunication { } } catch (IOException connectException) { // Unable to connect; close the socket and get out - stopSearching(); + disconnect(false); setBtStatus(BT_STATUS_CODE.BT_NO_DEVICE_FOUND); } } @@ -116,7 +112,7 @@ public class BluetoothCustomOpenScale extends BluetoothCommunication { } @Override - public void stopSearching() { + public void disconnect(boolean doCleanup) { if (btSocket != null) { if (btSocket.isConnected()) { try { diff --git a/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothIhealthHS3.java b/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothIhealthHS3.java index 2b3f15a2..470a628f 100644 --- a/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothIhealthHS3.java +++ b/android_app/app/src/main/java/com/health/openscale/core/bluetooth/BluetoothIhealthHS3.java @@ -27,7 +27,6 @@ import com.health.openscale.core.datatypes.ScaleMeasurement; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.Set; import java.util.UUID; import java.util.Date; import java.util.Arrays; @@ -74,24 +73,22 @@ public class BluetoothIhealthHS3 extends BluetoothCommunication { } @Override - public void startSearching(String deviceName) { + public void connect(String hwAddress) { -// Log.w("openscale","iHealth HS3 - startSearching "+deviceName); +// Log.w("openscale","iHealth HS3 - connect "+hwAddress); if (btAdapter == null) { setBtStatus(BT_STATUS_CODE.BT_NO_DEVICE_FOUND); return; } - Set pairedDevices = btAdapter.getBondedDevices(); - // Log.w("openscale","about to start searching paired devices"); - for (BluetoothDevice device : pairedDevices) { + for (BluetoothDevice device : btAdapter.getBondedDevices()) { // check if we can found bluetooth device name in the pairing list // if (device != null ) { Log.w("openscale","Looking at device "+device.getName()); } ; - if (device != null && device.getName().equals(deviceName)) { + if (device != null && device.getAddress().equals(hwAddress)) { btDevice = device; try { @@ -118,7 +115,7 @@ public class BluetoothIhealthHS3 extends BluetoothCommunication { } } catch (IOException connectException) { // Unable to connect; close the socket and get out - stopSearching(); + disconnect(false); setBtStatus(BT_STATUS_CODE.BT_NO_DEVICE_FOUND); } } @@ -133,9 +130,9 @@ public class BluetoothIhealthHS3 extends BluetoothCommunication { } @Override - public void stopSearching() { + public void disconnect(boolean doCleanup) { - Log.w("openscale","HS3 - stopSearching"); + Log.w("openscale","HS3 - disconnect"); if (btSocket != null) { if (btSocket.isConnected()) { try { diff --git a/android_app/app/src/main/java/com/health/openscale/gui/MainActivity.java b/android_app/app/src/main/java/com/health/openscale/gui/MainActivity.java index 63722c36..a5c3ce9a 100644 --- a/android_app/app/src/main/java/com/health/openscale/gui/MainActivity.java +++ b/android_app/app/src/main/java/com/health/openscale/gui/MainActivity.java @@ -18,11 +18,11 @@ package com.health.openscale.gui; import android.annotation.SuppressLint; import android.app.AlertDialog; +import android.bluetooth.BluetoothManager; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; -import android.content.pm.PackageManager; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; @@ -62,7 +62,7 @@ import com.health.openscale.gui.fragments.GraphFragment; import com.health.openscale.gui.fragments.OverviewFragment; import com.health.openscale.gui.fragments.StatisticsFragment; import com.health.openscale.gui.fragments.TableFragment; -import com.health.openscale.gui.utils.PermissionHelper; +import com.health.openscale.gui.preferences.BluetoothPreferences; import java.io.File; import java.lang.reflect.Field; @@ -196,6 +196,7 @@ public class MainActivity extends BaseAppCompatActivity @Override public void onDestroy() { prefs.unregisterOnSharedPreferenceChangeListener(this); + OpenScale.getInstance(getApplicationContext()).disconnectFromBluetoothDevice(); super.onDestroy(); } @@ -382,7 +383,12 @@ public class MainActivity extends BaseAppCompatActivity startActivity(intent); return true; case R.id.action_bluetooth_status: - invokeSearchBluetoothDevice(); + if (OpenScale.getInstance(getApplicationContext()).disconnectFromBluetoothDevice()) { + setBluetoothStatusIcon(R.drawable.ic_bluetooth_disabled); + } + else { + invokeConnectToBluetoothDevice(); + } return true; case R.id.importData: importCsvFile(); @@ -405,11 +411,19 @@ public class MainActivity extends BaseAppCompatActivity bluetoothStatus = menu.findItem(R.id.action_bluetooth_status); + BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); + boolean hasBluetooth = bluetoothManager.getAdapter() != null; + + if (!hasBluetooth) { + bluetoothStatus.setEnabled(false); + setBluetoothStatusIcon(R.drawable.ic_bluetooth_disabled); + } // Just search for a bluetooth device just once at the start of the app and if start preference enabled - if (firstAppStart && prefs.getBoolean("btEnable", false)) { - invokeSearchBluetoothDevice(); + else if (firstAppStart && prefs.getBoolean("btEnable", false)) { + invokeConnectToBluetoothDevice(); firstAppStart = false; - } else { + } + else { // Set current bluetooth status icon while e.g. orientation changes setBluetoothStatusIcon(bluetoothStatusIcon); } @@ -429,7 +443,7 @@ public class MainActivity extends BaseAppCompatActivity drawerToggle.onConfigurationChanged(newConfig); } - private void invokeSearchBluetoothDevice() { + private void invokeConnectToBluetoothDevice() { final OpenScale openScale = OpenScale.getInstance(getApplicationContext()); if (openScale.getSelectedScaleUserId() == -1) { @@ -437,34 +451,21 @@ public class MainActivity extends BaseAppCompatActivity return; } - if (openScale.stopSearchingForBluetooth()) { - setBluetoothStatusIcon(R.drawable.ic_bluetooth_disabled); + String deviceName = prefs.getString( + BluetoothPreferences.PREFERENCE_KEY_BLUETOOTH_DEVICE_NAME, "-"); + String hwAddress = prefs.getString( + BluetoothPreferences.PREFERENCE_KEY_BLUETOOTH_HW_ADDRESS, ""); + + if (deviceName.equals("-")) { + Toast.makeText(getApplicationContext(), R.string.info_bluetooth_no_device_set, Toast.LENGTH_SHORT).show(); return; } - String deviceName = prefs.getString("btDeviceName", "-"); + Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_try_connection) + " " + deviceName, Toast.LENGTH_SHORT).show(); + setBluetoothStatusIcon(R.drawable.ic_bluetooth_searching); - boolean permGrantedCoarseLocation = false; - - // Check if Bluetooth 4.x is available - if (!deviceName.equals("openScale_MCU")) { - permGrantedCoarseLocation = PermissionHelper.requestBluetoothPermission(this, false); - } else { - permGrantedCoarseLocation = PermissionHelper.requestBluetoothPermission(this, true); - } - - if (permGrantedCoarseLocation) { - if (deviceName.equals("-")) { - Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_no_device_set), Toast.LENGTH_SHORT).show(); - return; - } - - Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_try_connection) + " " + deviceName, Toast.LENGTH_SHORT).show(); - setBluetoothStatusIcon(R.drawable.ic_bluetooth_searching); - - if (!openScale.startSearchingForBluetooth(deviceName, callbackBtHandler)) { - Toast.makeText(getApplicationContext(), deviceName + " " + getResources().getString(R.string.label_bt_device_no_support), Toast.LENGTH_SHORT).show(); - } + if (!openScale.connectToBluetoothDevice(deviceName, hwAddress, callbackBtHandler)) { + Toast.makeText(getApplicationContext(), deviceName + " " + getResources().getString(R.string.label_bt_device_no_support), Toast.LENGTH_SHORT).show(); } } @@ -706,28 +707,6 @@ public class MainActivity extends BaseAppCompatActivity } } - @Override - public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { - boolean permissionGranted = true; - switch (requestCode) { - case PermissionHelper.PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION: - if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - invokeSearchBluetoothDevice(); - } else { - setBluetoothStatusIcon(R.drawable.ic_bluetooth_disabled); - permissionGranted = false; - } - break; - } - - if (!permissionGranted) { - Toast.makeText(getApplicationContext(), getResources().getString( - R.string.permission_not_granted), Toast.LENGTH_SHORT).show(); - } - - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - } - @SuppressLint("RestrictedApi") public static void disableShiftMode(BottomNavigationView view) { BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0); diff --git a/android_app/app/src/main/java/com/health/openscale/gui/preferences/BluetoothPreferences.java b/android_app/app/src/main/java/com/health/openscale/gui/preferences/BluetoothPreferences.java index 4fde20d7..b15823bc 100644 --- a/android_app/app/src/main/java/com/health/openscale/gui/preferences/BluetoothPreferences.java +++ b/android_app/app/src/main/java/com/health/openscale/gui/preferences/BluetoothPreferences.java @@ -83,7 +83,7 @@ public class BluetoothPreferences extends PreferenceFragment { } }, progressUpdatePeriod); - OpenScale.getInstance(getActivity()).stopSearchingForBluetooth(); + OpenScale.getInstance(getActivity()).disconnectFromBluetoothDevice(); btScanner.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() { @Override @@ -210,7 +210,7 @@ public class BluetoothPreferences extends PreferenceFragment { btScanner.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { - if (PermissionHelper.requestBluetoothPermission(getActivity(), true)) { + if (PermissionHelper.requestBluetoothPermission(getActivity())) { startBluetoothDiscovery(); } return true; diff --git a/android_app/app/src/main/java/com/health/openscale/gui/utils/PermissionHelper.java b/android_app/app/src/main/java/com/health/openscale/gui/utils/PermissionHelper.java index 54aabb5e..a8b7e7db 100644 --- a/android_app/app/src/main/java/com/health/openscale/gui/utils/PermissionHelper.java +++ b/android_app/app/src/main/java/com/health/openscale/gui/utils/PermissionHelper.java @@ -34,7 +34,7 @@ public class PermissionHelper { public final static int PERMISSIONS_REQUEST_ACCESS_READ_STORAGE = 2; public final static int PERMISSIONS_REQUEST_ACCESS_WRITE_STORAGE = 3; - public static boolean requestBluetoothPermission(final Activity activity, boolean BLE) { + public static boolean requestBluetoothPermission(final Activity activity) { final BluetoothManager bluetoothManager = (BluetoothManager) activity.getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter btAdapter = bluetoothManager.getAdapter(); @@ -42,18 +42,18 @@ public class PermissionHelper { Toast.makeText(activity.getApplicationContext(), "Bluetooth " + activity.getResources().getString(R.string.info_is_not_enable), Toast.LENGTH_SHORT).show(); - Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); - activity.startActivityForResult(enableBtIntent, 1); + if (btAdapter != null) { + Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + activity.startActivity(enableBtIntent); + } return false; } // Check if Bluetooth 4.x is available - if (BLE) { - if (!activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { - Toast.makeText(activity.getApplicationContext(), "Bluetooth 4.x " + activity.getResources().getString(R.string.info_is_not_available), Toast.LENGTH_SHORT).show(); - return false; - } - } + if (!activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { + Toast.makeText(activity.getApplicationContext(), "Bluetooth 4.x " + activity.getResources().getString(R.string.info_is_not_available), Toast.LENGTH_SHORT).show(); + return false; + } if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); @@ -68,13 +68,11 @@ public class PermissionHelper { } }); - AlertDialog dialog = builder.create(); - dialog.show(); - } else { - return true; + builder.show(); + return false; } - return false; + return true; } public static boolean requestReadPermission(final Activity activity) { diff --git a/android_app/app/src/main/res/values/strings.xml b/android_app/app/src/main/res/values/strings.xml index 320e6068..5625fefc 100644 --- a/android_app/app/src/main/res/values/strings.xml +++ b/android_app/app/src/main/res/values/strings.xml @@ -189,7 +189,7 @@ Week view Permission not granted - openScale requires permission to access the coarse location to search for Bluetooth devices + openScale requires permission to access the coarse location to search for Bluetooth devices. The permission can be revoked after the device is found. Information Next Press and hold to reorder