Android blue connectGatt()方法未在BluetoothGattCallback中报告任何内容。。。。?

Android blue connectGatt()方法未在BluetoothGattCallback中报告任何内容。。。。?,android,bluetooth-lowenergy,android-bluetooth,Android,Bluetooth Lowenergy,Android Bluetooth,谁能检查一下这个代码的问题吗。我已经实现了一个服务,并将BluetoothDevice对象传递给它(通过intent传递的BluetoothDevice对象中没有错误/问题)。然后,在onStartCommand()中,我调用deviceToConnect.connectGatt(this,false,mGattCallback)。但是我的BluetoothGattCallback()无法工作(无法打印任何内容)。代码简单明了。有人能帮我调试一下吗 编辑:我正在MainActivity()中执行

谁能检查一下这个代码的问题吗。我已经实现了一个服务,并将
BluetoothDevice
对象传递给它(通过intent传递的
BluetoothDevice
对象中没有错误/问题)。然后,在
onStartCommand()
中,我调用
deviceToConnect.connectGatt(this,false,mGattCallback)
。但是我的
BluetoothGattCallback()
无法工作(无法打印任何内容)。代码简单明了。有人能帮我调试一下吗

编辑:我正在
MainActivity()
中执行Le设备扫描,并将设备对象传递给服务以连接到设备

public class PairedBleService extends Service
{
    private BluetoothGatt mConnectedGatt;
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        super.onStartCommand(intent, flags, startId);

        BluetoothDevice deviceToConnect = (BluetoothDevice) intent.getParcelableExtra(DEVICE_TO_CONNECT);
        mConnectedGatt = deviceToConnect.connectGatt(this, false, mGattCallback);

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Service End", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
            Toast.makeText(getApplicationContext(), "Peripheral connected", Toast.LENGTH_LONG).show();
        } else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED) {
            Toast.makeText(getApplicationContext(), "Peripheral Disconnected", Toast.LENGTH_LONG).show();
        } else if (status != BluetoothGatt.GATT_SUCCESS) {
            gatt.disconnect();
        }
    }
}

编辑:我尝试将我的信标(外设)与标准android蓝牙s/w连接,在那里我可以建立连接。但在这里,它要求配对pin,一旦输入pin,它就被连接并显示在配对蓝牙设备中。是否有任何类似于
connectGatt
的方法可以向用户询问“配对pin”。。。我无法理解我缺少了什么。

您的onBind方法返回null,因此您的主要活动无法与您的服务通信

您的代码应符合以下要求:

@PaireBleService

public class LocalBinder extends Binder 
{
    PairedBleService getService() 
    {
        return PairedBleService.this;
    };
};

@Override
public IBinder onBind(Intent intent) 
{
    // TODO Auto-generated method stub
    return mBinder;
};

private final IBinder mBinder = new LocalBinder();
@主要活动

//put this inside onServiceConnected

PairedBleService bleService = ((PairedBleService.LocalBinder) service).getService();

// Your code for connecting with BLE device
....................................
....................................

编辑确实有帮助。您想在应用程序内配对

BluetoothDevice
从API级别19(4.4)起就有了一个
createBond()
方法,因此这就省去了4.3,它是第一个BLE Android版本,但剩下的不多了

这将为用户弹出PIN对话框。设备成功连接后,即可进行连接。要知道绑定是否已完成,您需要注册一个
广播接收器
,以收听
操作\u绑定\u状态\u更改
。进入的
意图
具有
额外的绑定状态
,可以是
绑定
绑定
无绑定


因此,在您的
onstart命令中
您想要
getBondState()
如果它是
BOND\u NON
您想要
createBond()
。如果是
BOND\u BONDING
则需要等待与
BroadcastReceiver
的连接,并在连接后进行连接。如果它是
BOND\u BOND
,那么您可以连接。

我也遇到了类似的问题。我将通过MAC地址检索Bluetooth设备,该设备在用户上次扫描后保存到SharedPrefs,这样我们可以在应用程序打开时自动连接到该设备

在获得Bluetooth设备后,我调用了
device.connectGatt(…)
,回调将永远不会被命中,连接尝试将永远挂起

事实证明,Android操作系统中有一个内部蓝牙设备缓存。重新启动手机并切换蓝牙开关似乎可以清除此缓存,并且任何过去的扫描结果都不再显示在缓存中

如果您尝试使用缓存中不再存在的
BluetoothDevice
调用
device.connectGatt(…)
,则
connectGatt
调用将永远挂起,并且不会命中您的回调

相反,您需要检查
蓝牙设备的
类型
。如果类型为
BluetoothDevice.DEVICE\u type\u UNKNOWN
,则需要在尝试连接之前执行BLE扫描,因为该设备已不在缓存中

下面是我的一段代码,它一劳永逸地解决了这个问题

//Retrieve the MAC address of the device you want to connect to...in my case I used SharedPreferences
val pairedMacAddress = AppPreferences.getStringPreference(this, AppPreferences.PREF_BT_MAC_ADDRESS)
val savedBleDevice = bluetoothManager.adapter.getRemoteDevice(pairedMacAddress)
Timber.i("BluetoothDevice type is: ${savedBleDevice.type}")

// Saved BLE device is no longer in the device cache, we need to scan for devices again in order to autoconnect.
if (savedBleDevice.type == BluetoothDevice.DEVICE_TYPE_UNKNOWN) {

    Timber.i("Scanning for BLE devices since the saved BLE device is no longer in the system's BT cache.")

    val macAddressFilter = ScanFilter.Builder()
            .setDeviceAddress(pairedMacAddress)
            .build()

    val scanSettings = ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build()

    bluetoothManager.adapter.bluetoothLeScanner.startScan(listOf(macAddressFilter), scanSettings, object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {

            Timber.w("Got scan results!")

            with(result.device) {
                Timber.i("Found BLE device! Name: ${name ?: "Unnamed"}, address: $address, going to connect now.")
                startBleConnection(this) // This calls device.connectGatt()
            }
        }

        override fun onScanFailed(errorCode: Int) {
            Timber.e("onScanFailed: code $errorCode")
        }
    })
} else {
    Timber.i("Saved BluetoothDevice is still in the BT cache. Auto-connecting!")
    startBleConnection(savedBleDevice) // This calls device.connectGatt()
}

Android上的蓝牙很有趣-祝你好运

你在哪里扫描设备?我在活动中扫描了设备,我正在将BluetoothDevice对象传递到服务以连接到它。你是否已无条件地发送Toast或登录onConnectionStateChange以确保它被调用?嗨@DouglasJones。。。我也试过了,但是没有可打印的祝酒词。。。请看问题的编辑部分。。。也许有帮助。你有解决办法吗?我也有同样的问题。谢谢你的回复vikram。。。但是我还不能理解。。因为我能够连接到服务,但BluetoothGattCallback未调用,即Toast消息未显示在onConnectionStateChange()中。。。。。。。。