蓝牙
一、设置权限
<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
二、布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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/open_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开蓝牙" />
<Button
android:id="@+id/close_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="关闭蓝牙" />
<Button
android:id="@+id/getName_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取本机蓝牙名称" />
<Button
android:id="@+id/nearby_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="扫描附近蓝牙" />
<Button
android:id="@+id/show_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="展示已配对设备" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/mynearbyReceiver_id"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/myshowReceiver_id"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
三、判断权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, 100);
}
四、打开,关闭蓝牙
openId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(intent);
}
});
closeId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
defaultAdapter.disable();
}
});
五、获取本机蓝牙名字
getNameId.setOnClickListener(new View.OnClickListener() {
<