下面小结下Android中使用蓝牙的几个步骤
1 导入相关的包:
import android.bluetooth.*;
2 设置好权限
<uses-permission android:name="android.permission.BLUETOOTH" />
如果要更多的高级用户权限设置,要这样
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
3 android中有个BluetoothAdapter的单例类,首先要用到它,即
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
之后要判断设备是否支持蓝牙,可以这样判断
- BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); if(bluetooth != null) { }
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); if(bluetooth != null) { }
如果不为null,则支持
还要判断用户是否启用蓝牙功能:
- if (bluetooth.isEnabled()) { } else{ }
if (bluetooth.isEnabled()) { } else{ }
4 接下来,我们显示个用户,如果启用了蓝牙,则显示蓝牙设备的名和状态
如果蓝牙设备没启用,也告诉用户
- String status; if (bluetooth.isEnabled()) { String mydeviceaddress = bluetooth.getAddress(); String mydevicename = bluetooth.getName(); status = mydevicename + ” : ” + mydeviceaddress; } else{ status = “Bluetooth is not Enabled.”; } Toast.makeText(this, status, Toast.LENGTH_LONG).show();
String status; if (bluetooth.isEnabled()) { String mydeviceaddress = bluetooth.getAddress(); String mydevicename = bluetooth.getName(); status = mydevicename + ” : ” + mydeviceaddress; } else{ status = “Bluetooth is not Enabled.”; } Toast.makeText(this, status, Toast.LENGTH_LONG).show();
这里使用getName()获得设备名,如果之前有打开
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
的话,可以这样设置蓝牙设备名:
bluetooth.setName("AndroidCoder");
5 显示蓝牙状态:
String state = bluetooth.getState(); status = mydevicename + ” : ” + mydeviceaddress + " : " + state;
其中,蓝牙状态有:
STATE_TURNING_ON
STATE_ON
STATE_TURNING_OFF
STATE_OFF