添加权限
<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.BLUETOOTH},100);
}
注册广播
Broad broad = new Broad();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(broad,intentFilter);
打开蓝牙
public void dk(View view) {
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(intent);
}
关闭蓝牙
public void gb(View view) {
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
if (defaultAdapter!=null){
defaultAdapter.disable();
}
}
蓝牙名字
public void bluename(View view) {
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
if (defaultAdapter!=null){
String name = defaultAdapter.getName();
Toast.makeText(this, ""+name, Toast.LENGTH_SHORT).show();
}
}
搜索已配对的蓝牙
public void select(View view) {
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
if (defaultAdapter!=null){
Set<BluetoothDevice> bondedDevices = defaultAdapter.getBondedDevices();
list.addAll(bondedDevices);
MyAdapter myAdapter = new MyAdapter(list, this);
re.setLayoutManager(new LinearLayoutManager(this));
re.setAdapter(myAdapter);
}
}
搜索附近
public void near(View view) {
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
if (defaultAdapter!=null){
defaultAdapter.startDiscovery();
}
}