Android 11 Java 蓝牙测试代码,用于搜索和显示蓝牙状态,并利用view显示出来
时间: 2024-02-21 14:57:37 浏览: 118
安卓蓝牙测试
5星 · 资源好评率100%
好的,以下是一个简单的 Android 11 Java 蓝牙测试代码,用于搜索和显示蓝牙状态,并利用 View 显示出来:
```
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mArrayAdapter;
private ListView mListView;
private TextView mTextView;
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
mTextView.setText("Bluetooth off");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
mTextView.setText("Turning Bluetooth off...");
break;
case BluetoothAdapter.STATE_ON:
mTextView.setText("Bluetooth on");
break;
case BluetoothAdapter.STATE_TURNING_ON:
mTextView.setText("Turning Bluetooth on...");
break;
}
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress();
mArrayAdapter.add(deviceName + "\n" + deviceHardwareAddress);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mTextView = findViewById(R.id.bluetooth_status_text_view);
mListView = findViewById(R.id.bluetooth_device_list_view);
mArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
mListView.setAdapter(mArrayAdapter);
// 注册广播接收器监听状态改变和发现新设备
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
// 检查蓝牙是否可用
if (mBluetoothAdapter == null) {
mTextView.setText("Bluetooth not available");
} else if (!mBluetoothAdapter.isEnabled()) {
mTextView.setText("Bluetooth off");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 0);
} else {
mTextView.setText("Bluetooth on");
}
// 搜索设备
mBluetoothAdapter.startDiscovery();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBroadcastReceiver);
}
}
```
注意事项:
1. 首先需要在 AndroidManifest.xml 文件中添加以下权限:
```
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
```
2. 在 activity_main.xml 文件中添加一个 TextView 和一个 ListView,分别用于显示蓝牙状态和搜索到的设备列表。
3. 在 onCreate() 方法中,获取默认的 BluetoothAdapter 实例,并通过注册广播接收器监听蓝牙状态改变和发现新设备的事件。
4. 检查蓝牙是否可用并开启搜索设备功能。
5. 在 onDestroy() 方法中,注销广播接收器。
阅读全文