Android開發學習之藍牙API

1、顯式開啟藍牙設備

Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,1);

2、隱式開啟/關閉藍牙設備

BluetoothAdapter mAdapter=BluetoothAdapter.getDefaultAdapter();
//開啟藍牙設備
mAdapter.enable();
//關閉藍牙設備
mAdapter.disable();

3、獲取已配對的藍牙設備

Set mDevices=mAdapter.getBondedDevices();
//獲取已配對的設備
if(mDevices.size()>0)
{
   for(BluetoothDevice mDevice : mDevices)
   {
	mView.append(mDevice.getName()+":"+mDevice.getAddress()+"\n");
   }
}

4、搜索藍牙設備

private final BroadcastReceiver receiver=new BroadcastReceiver()
{
    @Override
    public void onReceive(Context mContext, Intent intent) 
    {
	if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction()))
	{
	   BluetoothDevice mDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	   if(mDevice.getBondState()!=BluetoothDevice.BOND_BONDED)
	   {
		mView.append(mDevice.getName()+":"+mDevice.getAddress()+"\n");
	   }
	}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction()))
	{
		MainActivity.this.setProgressBarIndeterminateVisibility(false);
	}
     }
};


//藍牙動作監聽廣播
IntentFilter mFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(receiver, mFilter);
//藍牙動作監聽結束廣播
mFilter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(receiver, mFilter);

發佈留言