android 藍牙4.0搜索功能支持所有品牌的手機

一、老的方法:
// 註冊廣播接收器。
// 接收藍牙發現


IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver1, filterFound);

IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(mReceiver1, filterStart);

IntentFilter filterFinish = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver1, filterFinish);

if(藍牙是否連接){
   mBluetoothAdapter.startDiscovery();
}

 

// 廣播接收發現藍牙設備


    private BroadcastReceiver mReceiver1 = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                LogUtil.it(TAG, "開始掃描...");
            }

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {

                  // 發現藍牙添加到ListView中

                }
            }

            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                LogUtil.it(TAG, "掃描結束.");

                if(沒有連接在搜索藍牙){
                    mScanning2= mBluetoothAdapter.startDiscovery();
                }

            }
        }
    };

//銷燬藍牙搜索。

unregisterReceiver(mReceiver1);

//取消藍牙搜索。
mBluetoothAdapter.cancelDiscovery();

新的方法:

   //搜索藍牙方法。

  boolean mScannings =false;

if (是否搜索藍牙) {
    if (mBluetoothAdapter.isEnabled()) {
 if (mScannings) return;
        mScannings = true;

        mBluetoothAdapter.startLeScan(mLeScanCallbacks);
    }
} else {
    mBluetoothAdapter.stopLeScan(mLeScanCallbacks);
    mScannings = false;
}

 

private BluetoothAdapter.LeScanCallback mLeScanCallbacks = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
          
            if(是否支持藍牙的類型)){

             //ListView Item 體現在界面中。
            }

        }
    };

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章