2011-06-24 80 views

回答

7

Find The Devices in the Range by using Bluetooth programmatically.

是的,你可以做到這一點使用BroadcastReceiver,看看下面的代碼,它會幫助你。

開始搜索

mBluetoothAdapter.startDiscovery(); 
mReceiver = new BroadcastReceiver() { 
public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 

查找設備

if (BluetoothDevice.ACTION_FOUND.equals(action)) 
    { 
     // Get the BluetoothDevice object from the Intent 
     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
     // Add the name and address to an array adapter to show in a ListView 
     mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
    } 
    } 
}; 

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
registerReceiver(mReceiver, filter); 
+3

+1爲已接受的答案。 – MKJParekh

1

創建撒施接收器類似下面,並添加你可能想使用方法startDiscovery設備信息

private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
ArrayList<HashMap<String, String> arl = new ArrayList<HashMap<String, String>();  
      // 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); 
       // If it's already paired, skip it, because it's been listed already 
       HashMap<String, String> deviceMap = new HashMap<String, String>(); 
       deviceMap.put(device.getName(), device.getAddress()); 
       arl.add(deviceMap); 

      // When discovery is finished, change the Activity title 
      } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
       setProgressBarIndeterminateVisibility(false); 
       setTitle(R.string.select_device); 
       if (mNewDevicesArrayAdapter.getCount() == 0) { 
        String noDevices = getResources().getText(R.string.none_found).toString(); 
        mNewDevicesArrayAdapter.add(noDevices); 
       } 
      } 
     } 


    }; 
+0

感謝蘇尼爾爲u'r response.this代碼不能正常工作,請發送完整的代碼。 – kiran

相關問題