android之蓝牙

来源:互联网 发布:nyaa的域名 编辑:程序博客网 时间:2024/04/28 20:24
public class Main extends Activity {private BluetoothAdapter bluetoothAdapter;private TextView tvDevices;private BluetoothAdapter mBluetoothAdapter;@Overridepublic 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");}}//注册用于接收已搜索到的蓝牙设备的ReceiverIntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);this.registerReceiver(receiver, filter);//注册搜索完成时的Receiverfilter = 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() {@Overridepublic 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("搜索蓝牙设备");}}};}



原创粉丝点击