一、Discoverydevice.java
public class Discoverydevice extends AppCompatActivity {private DeviceAdapter mAdapter2;private final List<DeviceClass> mbondDeviceList = new ArrayList<>();//搜索到的所有已绑定设备保存为列表private final List<DeviceClass> mfindDeviceList = new ArrayList<>();//搜索到的所有未绑定设备保存为列表private final BluetoothController mbluetoothController = new BluetoothController();private Toast mToast;private Button button;private BluetoothAdapter bluetoothAdapter;@SuppressLint("MissingPermission")@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_discoverydevice);bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();/* View rootView = findViewById(android.R.id.content);开始扫描蓝牙设备View updatedView = findDevice(rootView);*/button = findViewById(R.id.button1);button.setOnClickListener(v -> {init_Filter();//初始化广播并打开Init_listView();//初始化设备列表findDevice(v);});ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);return insets;});}//初始化蓝牙权限private void Init_Bluetooth() {mbluetoothController.enableVisibily(this);//让其他蓝牙看得到我mbluetoothController.turnOnBlueTooth(this, 0);//打开蓝牙}//初始化列表,适配器的加载public void Init_listView() {mAdapter2 = new DeviceAdapter(Discoverydevice.this, R.layout.device_item, mfindDeviceList);ListView listView2 = findViewById(R.id.listview2);listView2.setAdapter(mAdapter2);mAdapter2.notifyDataSetChanged();listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {@SuppressLint("MissingPermission")@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {DeviceClass device = mfindDeviceList.get(position); // 获取点击的设备信息String deviceAddress = device.getbAdress();String deviceName= device.getbName();Intent resultIntent = new Intent( );resultIntent.putExtra("bluetoothName", deviceName);resultIntent.putExtra("bluetoothAddress", deviceAddress);// 设置结果代码为 RESULT_OK,表示连接成功setResult(Discoverydevice.RESULT_OK, resultIntent);// 关闭当前活动finish();showToast("连接中...");}});Init_Bluetooth();}//开启广播private void init_Filter() {IntentFilter filter = new IntentFilter();filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); //连接蓝牙,断开蓝牙//开始查找filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//结束查找filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//查找设备 蓝牙发现新设备(未配对的设备)filter.addAction(BluetoothDevice.ACTION_FOUND);//设备扫描模式改变filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//绑定状态 设备配对状态改变filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);//在系统弹出配对框之前(确认/输入配对码)filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);//最底层连接建立filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);//最底层连接断开filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); //BluetoothAdapter连接状态filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); //BluetoothHeadset连接状态filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED); //BluetoothA2dp连接状态registerReceiver(receiver, filter);}//广播内容private final BroadcastReceiver receiver = new BroadcastReceiver() {@SuppressLint("MissingPermission")@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//开始查找if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {change_Button_Text("搜索中...", "DISABLE");
// showToast("搜索中..." );mfindDeviceList.clear();mAdapter2.notifyDataSetChanged(); //刷新列表适配器,将内容显示出来
// }}//结束查找else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// showToast("搜索设备..." );change_Button_Text("扫描设备", "ENABLE");}//查找设备else if (BluetoothDevice.ACTION_FOUND.equals(action)) {change_Button_Text("搜索中...", "DISABLE");
// showToast("搜索中..." );if (device != null && device.getName() != null && !device.getName().isEmpty()) {change_Button_Text("搜索中...", "DISABLE");// showToast("搜索中...");//查找到一个设备且设备名不为空就添加到列表类中mfindDeviceList.add(new DeviceClass(device.getName(), device.getAddress()));mAdapter2.notifyDataSetChanged(); //刷新列表适配器,将内容显示出来show_bondDevice();}}//设备扫描模式改变else if (BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, 0);if (scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {showToast("true");} else {showToast("false");}} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if (remoteDevice == null) {return;}int status = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, 0);if (status == BluetoothDevice.BOND_BONDED) {showToast("已绑定---" + remoteDevice.getName());} else if (status == BluetoothDevice.BOND_BONDING) {showToast("正在绑定---" + remoteDevice.getName());} else if (status == BluetoothDevice.BOND_NONE) {showToast("未绑定---" + remoteDevice.getName());}}}};//点击开始查找蓝牙设备public void findDevice(View view) {mbluetoothController.findDevice();}// 判断是否连接 显示已连接设备信息private void show_bondDevice() {bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();BluetoothProfile.ServiceListener profileListener = new BluetoothProfile.ServiceListener() {@SuppressLint("MissingPermission")@Overridepublic void onServiceConnected(int profile, BluetoothProfile proxy) {if (profile == BluetoothProfile.A2DP) {List<BluetoothDevice> devices = proxy.getConnectedDevices();if (!devices.isEmpty()) {BluetoothDevice connectedDevice = devices.get(0);mbondDeviceList.clear();mbondDeviceList.add(new DeviceClass(connectedDevice.getName(), connectedDevice.getAddress()));// button.setText(text);} else {// 展示已经配对的蓝牙设备show_bondDeviceList();}}}@Overridepublic void onServiceDisconnected(int profile) {// 展示已经配对的蓝牙设备show_bondDeviceList();}};bluetoothAdapter.getProfileProxy(Discoverydevice.this, profileListener, BluetoothProfile.A2DP);}// 未连接@SuppressLint("MissingPermission")private void show_bondDeviceList() {mbondDeviceList.clear();}//点击按键搜索后按键的变化private void change_Button_Text(String text, String state) {if ("ENABLE".equals(state)) {button.setEnabled(true);button.getBackground().setAlpha(255); //0~255 之间任意调整button.setTextColor(ContextCompat.getColor(this, R.color.black));} else {button.setEnabled(false);button.getBackground().setAlpha(150); //0~255 之间任意调整button.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));}button.setText(text);}//设置toast的标准格式private void showToast(String text) {if (mToast == null) {mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);mToast.show();} else {mToast.setText(text);mToast.show();}}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(receiver);}}
二、 activity_discoverydevice.xml.
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#eeeeee"android:orientation="vertical"tools:context=".Discoverydevice"><Buttonandroid:id="@+id/button1"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@drawable/button_style"android:text="扫描设备"android:textColor="#000000" /><TextViewandroid:id="@+id/textView1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="50px"android:text="附近设备" /><ListViewandroid:id="@+id/listview2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="20px"android:background="@drawable/listview_style1" />
</LinearLayout>