1、开启蓝牙与搜索设备
1.1、蓝牙权限及蓝牙功能的开启
1.1.1、蓝牙权限的声明
新建一个工程,名为BluetoothDemo
,首先在AndroidManifest
中添加用到的蓝牙权限,这样我们就可以在应用中访问蓝牙设备、扫描附近蓝牙设备及通过蓝牙进行通信的功能。
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
1.1.2、蓝牙的开启
思路:
1. 利用BluetoothAdapter
是否为null来判断设备是否支持蓝牙(在onCreate函数中)
2. 然后调用isEnable()
来检查当前是否已启用蓝牙,若此方法返回false,则表示蓝牙处于停用状态,则通过BluetoothAdapter.ACTION_REQUEST_ENABLE
向系统设置发出启用蓝牙的请求(无需停止应用)以开启蓝牙。(在onStart函数中)
1.修改MainActivity
代码
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Bluetooth";
private BluetoothAdapter mBluetoothAdapter;
public static final int REQUEST_CODE_BT = 6;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Device not support bluetooth.");
} else {
Toast.makeText(this, "设备支持蓝牙!", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onStart() {
super.onStart();
if (!mBluetoothAdapter.isEnabled()) {
//向系统请求开启蓝牙
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_CODE_BT);
} else {
Toast.makeText(this, "蓝牙已开启!", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_BT) {
Toast.makeText(this, "蓝牙已开启!", Toast.LENGTH_SHORT).show();
}
}
}
2.在真机上运行该应用,可以手动打开蓝牙,演示略。
1.2、查看已配对的蓝牙设备
- 在执行设备查找之前,有必要先查看一下目前设备是否是以前配对过的设备(即存在于已配对设备的列表中),可以通过getBondedDevices():可以返回已配对设备的一组BluetoothDevice
- 当我们连接一个设备时,首先会去搜索附近的设备,如果是以前配对过的设备,会在已配对设备中去查找,如果是新设备的话我们就要调用startDiscovery()去发现设备,这样就能查找到新设备。该进程为异步进程,该方法会立即返回一个布尔值,指示是否已成功启动发现操作,而发现进程通常包含约12秒的查询扫描
1.布局文件activity_main
代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btnPairedDevice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="已配对设备" />
<Button
android:id="@+id/btnScanDevice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="扫描附近蓝牙设备" />
</LinearLayout>
2.继续编写MainActivity的代码:
private Button mBtnPairedDevice;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnPairedDevice = findViewById(R.id.btnPairedDevice);
mBtnPairedDevice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
Log.d(TAG, "Device name " + device.getName());
Log.d(TAG, "Device address " + device.getAddress());
}
}
});
}
3.准备两部手机,将蓝牙连接上,运行应用到另一台真机,单击已配对设备
按钮,log打印结果如下:
1.3、扫描附近蓝牙设备
1.继续编写MainActivity
代码,添加如下代码(将TAG
改为Bluetooth-scan
):
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Bluetooth-scan";
private BluetoothAdapter mBluetoothAdapter;
private Button mBtnScanDevice;
private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "Action: " + action);
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "Action: " + action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "New device name " + device.getName());
Log.d(TAG, "New device address " + device.getAddress());
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.d(TAG, "Discovery have done!");
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnScanDevice = findViewById(R.id.btnScanDevice);
mBtnScanDevice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
}
});
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBluetoothReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothReceiver);
}
}
2.运行应用,这次我用了一台魅族手机,然后点击已配对设备
按钮,找到三个已配对设备,分别为:小米手机、JABRA CLEAR、小米 note3,接着点击扫描附近蓝牙设备
按钮,扫描到了小米 note3,并输出了Discovery have done!
,这说明接收到了那两个广播。
经典蓝牙的相关知识请参考谷歌官方文档:
https://developer.android.google.cn/guide/topics/connectivity/bluetooth