public class Main extends Activity {
private BluetoothAdapter bluetoothAdapter;
private TextView tvDevices;
private BluetoothAdapter mBluetoothAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
/**在蓝牙设备连接之前,你需要核实,你的device是否support蓝牙
*If so, ensure that is enabled;
*If Bluetooth is supported, but disabled,
*then you can request that the user enable Bluetooth without leaving your application.
*/
/**
* This setup is accomplished in two steps, using the BluetoothAdapter.
*/
/**1.Get the BluetoothAdapter
*
*If getDefaultAdapter() returns null,
*then the device does not support Bluetooth and your story ends here.
*/
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null){
Toast.makeText(this, "Device does not support Bluetooth", Toast.LENGTH_LONG).show();
}
/**2.Enable Bluetooth
*
* The REQUEST_ENABLE_BT constant passed to startActivityForResult()
* is a locally defined integer (which must be greater than 0)
*/
if(!mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
tvDevices = (TextView) findViewById(R.id.tvDevices);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//获得已绑定的蓝牙设备
Set<BluetoothDevice> pairedDevices = bluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
//将已绑定的蓝牙设备的名称和地址显示在TextView控件中
tvDevices.append(device.getName() + ":" + device.getAddress()
+ "\n");
}
}
//注册用于接收已搜索到的蓝牙设备的Receiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(receiver, filter);
//注册搜索完成时的Receiver
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(receiver, filter);
}
public void onClick_Search(View view){
setProgressBarIndeterminateVisibility(true);
setTitle("正在扫描...");
//如果此时正好在搜索,先取消搜索
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
//开始搜索蓝牙设备
bluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//获得已搜索到的蓝牙设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//搜索到的设备不是已绑定的蓝牙设备
if (device.getBondState() != BluetoothDevice.BOND_BONDED){
//将搜索到新蓝牙设备显示在TextView控件中
tvDevices.append("Name="+device.getName() + "\nAddress="
+ device.getAddress() + "\n\n");
}
}
//搜索完成
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle("搜索蓝牙设备");
}
}
};
}