程序发现范围内的蓝牙设备并在android中显示它们

时间:2013-03-17 11:58:29

标签: android bluetooth device discovery

我想设计一个蓝牙遥控器,但是当我点击搜索按钮时,它不会搜索设备,或者可能会搜索设备,但不会显示任何设备。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Button button1 = (Button) findViewById(R.id.button1);
    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    final ArrayAdapter<String> mArrayAdapter=new ArrayAdapter<String>(this,R.layout.activity_main);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(!mBluetoothAdapter.isEnabled())
            {
                Intent enableBtIntent=new 
                        Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
            }
            mBluetoothAdapter.startDiscovery(); 
            BroadcastReceiver 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);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

0 个答案:

没有答案