BLE connectGatt()方法在BluetoothGattCallback中没有报告任何内容....?

时间:2014-12-05 12:38:07

标签: android bluetooth-lowenergy android-bluetooth

有人可以用这段代码检查问题。我已经实现了一个服务并将BluetoothDevice对象传递给它(BluetoothDevice对象传递意图没有错误/问题)。然后,在onStartCommand()中,我正在呼叫deviceToConnect.connectGatt(this,false,mGattCallback)。但我的BluetoothGattCallback()无效(不打印任何内容)。代码简单直接。有人可以帮我调试它。

编辑:我在MainActivity()进行Le device Scan并将设备对象传递给服务以连接到设备。

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连接,然后我可以建立连接。但是在那里它要求配对引脚和一旦把它连接并显示在配对蓝牙设备中。有没有像connectGatt这样的方法我们可以问"配对pin"给用户......我无法理解我所缺少的东西。

3 个答案:

答案 0 :(得分:1)

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

您的代码应符合以下规定,

@ PairedBleService

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
....................................
....................................

答案 1 :(得分:1)

编辑确实有帮助。你想在应用程序中配对...

从API级别19(4.4)开始,

BluetoothDevice有一个createBond()方法,因此省略了4.3这是第一个BLE Android版本,但其中很多都没有。< / p>

这应该弹出用户的PIN对话框。设备成功粘合后,即可连接。要知道绑定何时完成,您需要注册BroadcastReceiver来收听ACTION_BOND_STATE_CHANGED。进来的IntentEXTRA_BOND_STATE,可以是BOND_BONDEDBOND_BONDING_BOND_NONE

因此,在您onStartCommand getBondState()BOND_NON如果createBond() BOND_BONDING,您希望BroadcastReceiverBOND_BONDED如果是{{1}},则需要等待与{{1}}的绑定,并在绑定后进行连接。如果是{{1}},那么您可以连接。

答案 2 :(得分:0)

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

在获得 BluetoothDevice 后,我调用了 device.connectGatt(...),并且永远不会命中回调并且连接尝试将永远挂起。

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

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

相反,您需要检查 typeBluetoothDevice。如果类型为 BluetoothDevice.DEVICE_TYPE_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 上的蓝牙很有趣 - 祝你好运!