欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  技术分享

Android蓝牙4.0开发_蓝牙开发实例源码下载

程序员文章站 2022-03-01 12:53:14
...

分享一个集成目前主流蓝牙的demo、android蓝牙4.0开发、项目中使用到了搜索BLE终端和读写BLE终端、另外还有在程序里面开房蓝牙、在Demo里面还处理了收到BLE终端数据交互的事件、代码里都有中文注释、要读性应该非常好的、应该会对开发有一定帮助、有兴趣的哥们可以下载看看

Android蓝牙4.0开发_蓝牙开发实例源码下载


onCreate代码

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

    // Use this check to determine whether BLE is supported on the device.  Then you can
    // selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    }

    // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
    // BluetoothAdapter through BluetoothManager.
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();
    
    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    //开启蓝牙
    mBluetoothAdapter.enable();
    
    mBLE = new BluetoothLeClass(this);
    if (!mBLE.initialize()) {
        Log.e(TAG, "Unable to initialize Bluetooth");
        finish();
    }
    //发现BLE终端的Service时回调
    mBLE.setOnServiceDiscoverListener(mOnServiceDiscover);
    //收到BLE终端数据交互的事件
    mBLE.setOnDataAvailableListener(mOnDataAvailable);
}


收到BLE终端数据交互的事件

/**
 * 收到BLE终端数据交互的事件
 */
private BluetoothLeClass.OnDataAvailableListener mOnDataAvailable = new OnDataAvailableListener(){

    /**
     * BLE终端数据被读的事件
     */
    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) 
            Log.e(TAG,"onCharRead " gatt.getDevice().getName()
                     " read "
                     characteristic.getUuid().toString()
                     " -> "
                     Utils.bytesToHexString(characteristic.getValue()));
    }
    
    /**
     * 收到BLE终端写入数据回调
     */
    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic) {
        Log.e(TAG,"onCharWrite " gatt.getDevice().getName()
                 " write "
                 characteristic.getUuid().toString()
                 " -> "
                 new String(characteristic.getValue()));
    }
};


最后给贴上Demo的源代码、希望对大家有用、有兴趣的哥们可以下载看看

源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1dDk9onZ 密码: 91qn