标签:android bluetooth bluetoothadapter bluetoothdevice
(1)要想使用android 手机的Bluetooth,需要在androidmanifest文件中加入使用蓝牙的权限。
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
(2)要确定是否存在可以使用的蓝牙设备,若存在判断蓝牙设备是否打开,如果没有打开的话,就打开蓝牙
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
Toast.makeText(MainActivity.this, "此设备不支持蓝牙传输功能!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "此设备支持蓝牙传输功能!", Toast.LENGTH_SHORT).show();
if (!mBluetoothAdapter.isEnabled())
{
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
enableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
Toast.makeText(MainActivity.this, "蓝牙设备已经打开!", Toast.LENGTH_SHORT).show();
注意:1)BluetoothAdapter 就代表本地蓝牙设备,用getDefaultAdapter()获取本地蓝牙设备,其返回值如果为空表示不存在蓝牙设备,否则就说明存在蓝牙设备2)用isEnabled()方法来确定蓝牙设备是否打开,若没有打开返回值为false,需要重新调用startActivityForResult(enableIntent, REQUEST_ENABLE_BT);方法来打开蓝牙设备。在打开蓝牙设备的过程中会弹出对话框,询问蓝牙通信的权限、
(3)查找已经配对过的蓝牙设备用getBondedDevices();方法,并把它放在集合中,显示在textview中
Set<BluetoothDevice> pairedDevices=mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0){
for (BluetoothDevice bluetoothDevice : pairedDevices) {
textview1.append(bluetoothDevice.getName() + ":"
+ bluetoothDevice.getAddress() + "\n\n");
}
}可以看我接下来的一篇文章搜索附近的已经打开的蓝牙设备
android 打开蓝牙设备 显示已经配对的蓝牙设备 ,并将已配对的蓝牙设备显示在textview中,布布扣,bubuko.com
android 打开蓝牙设备 显示已经配对的蓝牙设备 ,并将已配对的蓝牙设备显示在textview中
标签:android bluetooth bluetoothadapter bluetoothdevice
原文地址:http://blog.csdn.net/liuzuyi200/article/details/37740401