简体   繁体   中英

Trying to get BluetoothAdapter; Cannot resolve method 'GetSystemService(java.lang.String)'

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);
    }

}

在此处输入图片说明

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM