2014-05-25 77 views
0

我想分析心率監測器的心率。爲此,我想保存上次使用的設備並將其與找到的設備進行比較。因爲找到設備需要一段時間,所以mDevice保持爲空。我需要做些什麼才能正確更新mDevice?如何處理android中的數據流

private ArrayList<BluetoothDevice> mDeviceList; 
private BluetoothAdapter mBluetoothAdapter; 
private boolean mScanning; 
private Handler mHandler; 
private BluetoothDevice mDevice; 

private static final int REQUEST_ENABLE_BT = 1; 
// Stops scanning after 10 seconds. 
private static final long SCAN_PERIOD = 10000; 

    @Override 
protected void onStart() { 
    super.onStart(); 
    // Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled, 
    // fire an intent to display a dialog asking the user to grant permission to enable it. 
    if (!mBluetoothAdapter.isEnabled()) { 
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
    } 


    // Initializes list view adapter. 
    mDeviceList = new ArrayList<BluetoothDevice>(); 
    scanLeDevice(true); 

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
    final String adress = prefs.getString(getString(R.string.device_address), ""); 

    for(BluetoothDevice b : mDeviceList){ 
     if(b.getAddress().equals(adress)){ 
      mDevice = b; 
     } 
    } 
    if(mDevice != null) 
     Log.e(TAG, mDevice.getAddress()); 

}

從谷歌手動拍攝:

private void scanLeDevice(final boolean enable) { 
    if (enable) { 
     // Stops scanning after a pre-defined scan period. 
     mHandler.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       mScanning = false; 
       mBluetoothAdapter.stopLeScan(mLeScanCallback); 
       invalidateOptionsMenu(); 
      } 
     }, SCAN_PERIOD); 
     mScanning = true; 
     mBluetoothAdapter.startLeScan(mLeScanCallback); 
    } else { 
     mScanning = false; 
     mBluetoothAdapter.stopLeScan(mLeScanCallback); 
    } 
    invalidateOptionsMenu(); 
} 

// Device scan callback. 
private BluetoothAdapter.LeScanCallback mLeScanCallback = 
     new BluetoothAdapter.LeScanCallback() { 

      @Override 
      public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         if(!mDeviceList.contains(device)){ 
          mDeviceList.add(device); 
         } 
        } 
       }); 
      } 
     }; 

我希望這是足夠的信息。如果丟失了某些東西,請隨時詢問

回答

0

掃描是一種背景活動,嘗試在啓動後立即查看結果,而不是等待結束。您可能希望將檢查代碼直接放入onLeScan回撥中,並在您看到所需設備後立​​即停止掃描。

如果您已經擁有設備的詳細信息,只需嘗試直接連接,您也可以嘗試不要一起進行掃描。在連接之前需要掃描的詳細信息在文檔中並不完全清楚,因此您需要準備好嘗試一下,因爲它仍然太過片質。

0

只需將你的代碼中你試圖找到最後一個設備(一切都在onStart()SharedPreferences prefs後...)後你已經在年底發現的設備,例如您可運行(後invalidateOptionsMenu();