本系列笔记概述
蓝牙传输优势:功耗低,传输距离还可以;
蓝牙聊天室案例
- Android中蓝牙设备的使用
- 蓝牙权限(本文的讲解内容之一)
- 蓝牙功能开启(本文的讲解内容之一)
- 搜索蓝牙设备(本文的讲解内容之一)
- 与外设搭建RFCOMM通道(射频通道)
- 蓝牙设备双向数据传输
蓝牙聊天室案例框架
-
蓝牙权限
执行蓝牙通信需要权限BLUETOOTH,
例如:请求连接、接收连接和传输数据等;如果需要启动设备 或 操作蓝牙设置,则需声明BLUETOOTH_ADMIN权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
-
设置蓝牙——获取BlueAdapter
使用蓝牙需用到BlueAdapter。表示设备自身的蓝牙适配器;
通过静态方法
BlueAdapter.getDefaultAdapter()
获得BlueAdapter;整个系统只有一个蓝牙适配器,application可使用此BlueAdapter对象与之交互;
如果
getDefaultAdapter()
返回null,则表示该设备不支持蓝牙,
例如:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null){
//Device does not support Bluetooth
}
-
启用蓝牙
调用
isEnable()
以检查当前是否已启用蓝牙;
如果此方法返回false
,则表示蓝牙处于停用状态;要请求启用蓝牙,将通过ACTION_REQUEST_ENABLE向系统设置
发出启用蓝牙的请求(无需停止应用),
例如:
...
private static final int REQUEST_ENABLE_BT = 10;//其是需要自己定义的局部常量。
...
if(mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
demo(查看本机是否支持蓝牙,蓝牙是否开启,没开启则请求):
- 新建一个项目,添加好如上述两个权限,编写MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "BluetoothChat";
private static final int REQUEST_ENABLE_BT = 10;//其是需要自己定义的局部常量。
private BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null){
//Device does not support Bluetooth
Log.e(TAG, "Device does not support Bluetooth");
}else {
Toast.makeText(this,"设备支持蓝牙!",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onStart() {
super.onStart();
if(!mBluetoothAdapter.isEnabled()){
//向系统请求开启蓝牙
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);//结果返回回调到onActivityResult()
}else {
//已经开启了蓝牙
Toast.makeText(this,"蓝牙已经开启",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_ENABLE_BT){
Toast.makeText(this,"蓝牙已经开启",Toa