查詢附近的藍芽裝置

先申報 BluetoothAdapter

BluetoothAdapter mBluetoothAdapter;

現在為 ACTION_FOUND 建立一個 BroadcastReceiver

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

    //Device found                
    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 list
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
  }
};

註冊 BroadcastReceiver

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

然後通過呼叫 startDiscovery 開始發現附近的藍芽裝置

mBluetoothAdapter.startDiscovery(); 

別忘了取消註冊 onDestroy 裡面的 BroadcastReceiver

unregisterReceiver(mReceiver);