2013-06-12 65 views
5

我正在嘗試查找可用的藍牙設備。Android搜索藍牙設備

這是我的OnClickListener,它在用戶嘗試搜索可用設備時被調用。

View.OnClickListener OnSearchDevices = new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      //Toast.makeText(context, "Search Devices", Toast.LENGTH_LONG).show(); 
      Log.d("Discovery", "Started"); 
      listOfDevices.clear(); 
      label.setText("Searching Available Devices..."); 
      label.setEnabled(false); 
     } 
    }; 

我還註冊了一個BroadcastReceiver。

private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 

      // When discovery finds a device 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       // Get the BluetoothDevice object from the Intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       Log.d("DeviceList" , device.getName() + "\n" + device.getAddress()); 
       MyBluetoothDevice tempDevice = new MyBluetoothDevice(); 
       tempDevice.setDeviceAddress(device.getAddress()); 
       tempDevice.setDeviceName(device.getName()); 
       listOfDevices.add(tempDevice); 
       mListAdapter.notifyDataSetChanged(); 
       // discovery is finished 
      } 
      else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 

       Log.d("Discovery","Finished"); 
       label.setEnabled(true); 
       if(listOfDevices.size() == 0) 
       { 
        label.setText("No Devices Available!"); 
        label.setTextColor(Color.parseColor("#FF0000")); 

       } 
       else 
       { 
        label.setText("Available Devices"); 
       } 

      } 
     } 
    }; 

但沒有任何反應。它沒有顯示任何東西。請幫忙。

回答

5

看起來您缺少對的呼叫mBluetoothAdapter.startDiscovery()

這可以解釋爲什麼你沒有得到任何結果,因爲適配器甚至沒有開始搜索設備。

您的代碼看起來好像沒什麼問題,否則。

+0

我在哪裏添加? – user2477164

+0

'onClick()' – Swayam

+0

太棒了!像魔術一樣工作!你搖滾男人! :d – user2477164