1. 程式人生 > >ANDROID藍芽4.0開發_藍芽開發例項原始碼下載

ANDROID藍芽4.0開發_藍芽開發例項原始碼下載

一個整合目前主流藍芽的demo、android藍芽4.0開發、專案中使用到了搜尋BLE終端和讀寫BLE終端、另外還有在程式裡面開房藍芽、在Demo裡面還處理了收到BLE終端資料互動的事件、程式碼裡都有中文註釋、要讀性應該非常好的、應該會對開發有一定幫助、有興趣的哥們可以下載看看

android藍芽4.0開發

onCreate程式碼

@Overridepublicvoid onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices
); mHandler =newHandler();// 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 =newBluetoothLeClass(this);if(!mBLE.initialize()){Log.e(TAG,"Unable to initialize Bluetooth"); finish();}//發現BLE終端的Service時回撥 mBLE.setOnServiceDiscoverListener(mOnServiceDiscover);//收到BLE終端資料互動的事件 mBLE.setOnDataAvailableListener(mOnDataAvailable);}

收到BLE終端資料互動的事件

/**
 * 收到BLE終端資料互動的事件
 */privateBluetoothLeClass.OnDataAvailableListener mOnDataAvailable =newOnDataAvailableListener(){/**
     * BLE終端資料被讀的事件
     */@Overridepublicvoid 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終端寫入資料回撥
     */@Overridepublicvoid onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic){Log.e(TAG,"onCharWrite " gatt.getDevice().getName()" write "
                 characteristic.getUuid().toString()" -> "newString(characteristic.getValue()));}};

最後給貼上Demo的原始碼、希望對大家有用、有興趣的哥們可以下載看看

若資源對你有幫助、瀏覽後有很大收穫、不妨小額打賞我一下、你的鼓勵是維持我不斷寫部落格最大動力

想獲取DD部落格最新程式碼、你可以掃描下方的二維碼、關注DD部落格微信公眾號(ddblogs)

如對資源有任何疑問或覺得仍然有很大的改善空間、可以對該博文進行評論、希望不吝賜教

感謝你的訪問、祝你生活愉快、工作順心、歡迎常來逛逛