0

I am following along with the BluetoothLE docs at Android Studio:

https://developer.android.com/guide/topics/connectivity/bluetooth-le#setup

My goal is to set up Bluetooth to be able to work with my java app.

Why am I getting the 'Cannot resolve method' error, and how do I resolve this? Also, why is 'mBluetoothAdapter' an unknown class if I just declared it as the variable name?

package com.august.sensorclient;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import java.lang.String;

public class BLEScanner {

    private BluetoothAdapter mBluetoothAdapter;


    // Initializes Bluetooth adapter.
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // Ensures Bluetooth is available on the device and it is enabled. If not,
    // displays a dialog requesting user permission to enable Bluetooth.
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

}

enter image description here

Solved: I BELIEVE THE REASON WHY MY CODE WAS NOT GETTING ERRORS WAS BECAUSE I WAS NOT ACTUALLY CALLING ANYTHING BECAUSE I WAS TRYING TO WRITE THIS CODE INTO THE CLASS AND NOT INTO AN ACTUAL FUNCTION.

  • Why don't you just use `BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();` – Parag Pawar Sep 07 '18 at 20:20
  • @ParagPawar that is a good question. I have just been copying from the Android docs. I looked into the .getDefaultAdapter method and don't see why that wont work. Thank you –  Sep 07 '18 at 20:26
  • You're welcome :) – Parag Pawar Sep 07 '18 at 20:30
  • @ParagPawar getDefaultAdapeter is Deprecated this method will continue to work, but developers are strongly encouraged to migrate to using BluetoothManager.getAdapter(), since that approach enables support for Context.createAttributionContext. – Romain DEQUIDT Feb 04 '22 at 21:37

1 Answers1

-1

Edit your code with

 BluetoothManager bluetoothAdapter = (BluetoothManager) 
 mContext.getSystemService(Context.BLUETOOTH_SERVICE);

to get the mContext you have to pass your activity context to BLEScanner class.

Or you can directly code like this

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Sana
  • 456
  • 3
  • 9