车机互联 - 蓝牙

车机互联 - 蓝牙

设置蓝牙名称
private void setBluetoothName(String newName) {
    String currentName = mBinding.tvBluetoothName.getText().toString();
    if (newName.isEmpty()) {
        Toast.makeText(fragment.getContext(), "名称不能为空", Toast.LENGTH_SHORT).show();
    } else if (newName.equals(currentName)) {
        Toast.makeText(fragment.getContext(), "名称与当前名称相同", Toast.LENGTH_SHORT).show();
    } else {
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.setName(newName);
            Log.d("BluetoothPopup", "Bluetooth name changed to: " + bluetoothAdapter.getName());
            Toast.makeText(fragment.getContext(), "蓝牙名称已更改为: " + newName, Toast.LENGTH_SHORT).show();
            mBinding.tvBluetoothName.setText(newName);
        } else {
            Toast.makeText(fragment.getContext(), "请先打开蓝牙", Toast.LENGTH_SHORT).show();
        }
    }
}
搜索蓝牙

搜索蓝牙设备,注册广播接收器。

// 搜索蓝牙设备
private void startBluetoothDiscovery() {
    if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
        // 显示加载动画
        mBinding.progressBar.setVisibility(View.VISIBLE);
        mBinding.tvSearchBluetoothCancel.setVisibility(View.VISIBLE);

        // 启动蓝牙搜索
        bluetoothAdapter.startDiscovery();

        // 注册广播接收器以获取搜索结果
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        fragment.getContext().registerReceiver(receiver, filter);

        // 显示可用设备视图
        hideAllDetailViews();
        mBinding.validDevice.setVisibility(View.VISIBLE);
    } else {
        Toast.makeText(fragment.getContext(), "请先打开蓝牙", Toast.LENGTH_SHORT).show();
    }
}

private void stopBluetoothDiscovery() {
    if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
        bluetoothAdapter.cancelDiscovery();
    }
    mBinding.progressBar.setVisibility(View.GONE);
    mBinding.tvSearchBluetoothCancel.setVisibility(View.GONE);
    // Toast.makeText(fragment.getContext(), "蓝牙搜索已取消", Toast.LENGTH_SHORT).show();
}

// 蓝牙搜索结果的广播接收器
private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @SuppressLint("MissingPermission")
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // 只显示未配对的设备
            if (device != null && device.getBondState() != BluetoothDevice.BOND_BONDED && !validList.contains(device)) {
                validList.add(device);
                bluetoothValidListAdapter.notifyDataSetChanged();
                Log.d("BluetoothPopup", "Found device: " + device.getName());
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            // 隐藏加载动画
            mBinding.progressBar.setVisibility(View.GONE);
            mBinding.tvSearchBluetoothCancel.setVisibility(View.GONE);
            Log.d("BluetoothPopup", "Bluetooth discovery finished");
        }
    }
};
蓝牙配对
// 蓝牙配对成功的广播接收器
private final BroadcastReceiver bondReceiver = new BroadcastReceiver() {
    @SuppressLint("MissingPermission")
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d("BluetoothPopup", "Broadcast received: " + action);
        if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            Log.d("BluetoothPopup", "Bond state changed");
            final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
            final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
            if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {
                    // 配对成功,添加到已配对设备列表
                    saveList.add(device);
                    bluetoothSaveListAdapter.notifyDataSetChanged();

                    // 自动连接设备
                    connectToDevice(device);

                    // 从可用设备列表中移除
                    validList.remove(device);
                    bluetoothValidListAdapter.notifyDataSetChanged();

                    Toast.makeText(fragment.getContext(), "配对成功", Toast.LENGTH_SHORT).show();
                    Log.d("BluetoothPopup", "Device paired successfully: " + device.getName());
                }
            }
        }
    }
};

// 蓝牙状态变化的广播接收器
private final BroadcastReceiver bluetoothStateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            if (state == BluetoothAdapter.STATE_ON) {
                // 蓝牙已打开,尝试自动连接已配对设备
                autoConnectDevices();
            }
        }
    }
};

蓝牙完整源码:

package com.fii.settings.view;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fii.settings.R;
import com.fii.settings.adapter.BluetoothConnectListAdapter;
import com.fii.settings.adapter.BluetoothSaveListAdapter;
import com.fii.settings.adapter.BluetoothValidListAdapter;
import com.fii.settings.databinding.PopuBluetoothSettingsBinding;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import android.os.Handler;
import android.os.Looper;

import razerdp.basepopup.BasePopupWindow;

public class BluetoothPopup extends BasePopupWindow implements BluetoothConnectListAdapter.OnItemClickListener, BluetoothSaveListAdapter.OnItemClickListener, BluetoothValidListAdapter.OnItemClickListener, BluetoothSaveListAdapter.OnDeleteClickListener {
    private final PopuBluetoothSettingsBinding mBinding;
    private Fragment fragment;
    private List<BluetoothDevice> saveList;
    private List<BluetoothDevice> connectList;
    private List<BluetoothDevice> validList;
    private BluetoothConnectListAdapter bluetoothConnectListAdapter;
    private BluetoothSaveListAdapter bluetoothSaveListAdapter;
    private BluetoothValidListAdapter bluetoothValidListAdapter;
    private BluetoothAdapter bluetoothAdapter;//蓝牙适配器
    private Handler handler = new Handler(Looper.getMainLooper());
    private BluetoothPopupListener listener;

    public interface BluetoothPopupListener {
        void onBluetoothStatusChanged(boolean isEnabled);
    }

    public void setBluetoothPopupListener(BluetoothPopupListener listener) {
        this.listener = listener;
    }

    @SuppressLint("MissingPermission")
    public BluetoothPopup(Fragment fragment) {
        super(fragment);
        this.fragment = fragment;
        View popupBle = this.createPopupById(R.layout.popu_bluetooth_settings);
        mBinding = PopuBluetoothSettingsBinding.bind(popupBle);
        setContentView(popupBle);

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Log.d("BluetoothPopup", "Bluetooth Adapter is enabled: " + bluetoothAdapter.isEnabled());

        mBinding.tvBluetoothName.setText(bluetoothAdapter.getName());
        mBinding.switchBluetooth.setChecked(bluetoothAdapter.isEnabled());

        initSaveBluetoothList();
        initConnectBluetoothList();
        initValidBluetoothList();
        mBinding.ivBluetoothClose.setOnClickListener(view -> dismiss());

        mBinding.tvSearchBluetooth.setOnClickListener(view -> {
            validList.clear(); //清空可用设备
            bluetoothValidListAdapter.notifyDataSetChanged(); //通知适配器数据已改变
            startBluetoothDiscovery(); //启动蓝牙搜索
        });
        mBinding.tvSearchBluetoothCancel.setOnClickListener(view -> stopBluetoothDiscovery());

        mBinding.ivEditBluetoothName.setOnClickListener(view -> {
            hideAllDetailViews();
            mBinding.modifyName.setVisibility(View.VISIBLE);
        });
        mBinding.tvOkName.setOnClickListener(view -> {
            String newName = mBinding.editBluetoothName.getText().toString();
            setBluetoothName(newName);
        });
        mBinding.tvCancelName.setOnClickListener(view -> mBinding.modifyName.setVisibility(View.GONE));

        // 蓝牙开关
        mBinding.switchBluetooth.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                if (!bluetoothAdapter.isEnabled()) {
                    bluetoothAdapter.enable();
                    Log.d("BluetoothPopup", "Bluetooth enabled");
                }
            } else {
                if (bluetoothAdapter.isEnabled()) {
                    bluetoothAdapter.disable();
                    Log.d("BluetoothPopup", "Bluetooth disabled");
                }
            }
            if (listener != null) {
                listener.onBluetoothStatusChanged(isChecked);
            }
        });

        hideAllDetailViews();

        // 注册配对成功的广播接收器
        IntentFilter bondFilter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        fragment.getContext().registerReceiver(bondReceiver, bondFilter);

        // 注册蓝牙状态变化的广播接收器
        IntentFilter bluetoothStateFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        fragment.getContext().registerReceiver(bluetoothStateReceiver, bluetoothStateFilter);

        // 自动连接之前配对过的设备
        autoConnectDevices();

        // 启动定期检查任务
        handler.post(autoConnectRunnable);
    }

    @SuppressLint("MissingPermission")
    private void initConnectBluetoothList() {
        connectList = new ArrayList<>();
        for (BluetoothDevice device : bluetoothAdapter.getBondedDevices()) {
            if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                connectList.add(device);
            }
        }
        mBinding.bluetoothConnectedList.setLayoutManager(new LinearLayoutManager(fragment.getContext()));
        bluetoothConnectListAdapter = new BluetoothConnectListAdapter(connectList, this);
        mBinding.bluetoothConnectedList.setAdapter(bluetoothConnectListAdapter);
    }

    @SuppressLint("MissingPermission")
    public void initSaveBluetoothList() {
        saveList = new ArrayList<>();
        Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
        if (pairedDevice != null) {
            for (BluetoothDevice device : pairedDevice) {
                saveList.add(device);
            }
        }
        mBinding.bluetoothSaveList.setLayoutManager(new LinearLayoutManager(fragment.getContext()));
        bluetoothSaveListAdapter = new BluetoothSaveListAdapter(saveList, this, this);
        mBinding.bluetoothSaveList.setAdapter(bluetoothSaveListAdapter);
    }

    public void initValidBluetoothList() {
        validList = new ArrayList<>();
        mBinding.bluetoothDeviceList.setLayoutManager(new LinearLayoutManager(fragment.getContext()));
        bluetoothValidListAdapter = new BluetoothValidListAdapter(validList, this);
        mBinding.bluetoothDeviceList.setAdapter(bluetoothValidListAdapter);
    }

    @Override
    public void onSaveItemClick(int position) {
        // 处理已配对设备列表项的点击事件
        BluetoothDevice device = saveList.get(position);
        connectToDevice(device);
    }

    private void connectToDevice(BluetoothDevice device) {
        if (device != null) {
            BluetoothProfile.ServiceListener serviceListener = new BluetoothProfile.ServiceListener() {
                @SuppressLint("MissingPermission")
                @Override
                public void onServiceConnected(int profile, BluetoothProfile proxy) {
                    try {
                        Method connectMethod = proxy.getClass().getMethod("connect", BluetoothDevice.class);
                        connectMethod.invoke(proxy, device);
                        Log.d("BluetoothPopup", "Connecting to device: " + device.getName());

                        // 将设备添加到已连接列表
                        connectList.add(device);
                        bluetoothConnectListAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    bluetoothAdapter.closeProfileProxy(profile, proxy);
                }

                @Override
                public void onServiceDisconnected(int profile) {

                }
            };
            bluetoothAdapter.getProfileProxy(fragment.getContext(), serviceListener, BluetoothProfile.A2DP);
        }
    }

    // 自动连接已配对设备
    @SuppressLint("MissingPermission")
    private void autoConnectDevices() {
        for (BluetoothDevice device : bluetoothAdapter.getBondedDevices()) {
            if (!isAudioProfileConnected(device, BluetoothProfile.A2DP)) {
                connectToDevice(device);
            }
        }
    }

    // 定期检查任务
    private Runnable autoConnectRunnable = new Runnable() {
        @Override
        public void run() {
            autoConnectDevices();
            handler.postDelayed(this, 3000);
        }
    };

    @SuppressLint("MissingPermission")
    @Override
    public void onConnectItemClick(int position) {
        // 处理已连接设备列表项的点击事件
        hideAllDetailViews();
        mBinding.clBluetoothConnectMsg.setVisibility(View.VISIBLE);
        BluetoothDevice device = connectList.get(position);
        mBinding.tvBluetoothConnectName.setText(device.getName());

        if (device != null) {
            final BluetoothDevice finalConnectedDevice = device;
            // 设置开关按钮的初始状态
            mBinding.switchPhoneAudio.setChecked(isAudioProfileConnected(finalConnectedDevice, BluetoothProfile.HEADSET));
            mBinding.switchMediaAudio.setChecked(isAudioProfileConnected(finalConnectedDevice, BluetoothProfile.A2DP));
            mBinding.switchBluetoothTethering.setChecked(isAudioProfileConnected(finalConnectedDevice, BluetoothProfile.HEALTH));

            // 设置断开连接按钮
            mBinding.tvCancelBluetooth.setOnClickListener(view -> {
                try {
                    Method removeBondMethod = BluetoothDevice.class.getMethod("removeBond");
                    boolean removed = (boolean) removeBondMethod.invoke(finalConnectedDevice);
                    if (removed) {
                        connectList.remove(position);
                        bluetoothConnectListAdapter.notifyItemRemoved(position);
                        hideAllDetailViews();
                        Toast.makeText(fragment.getContext(), "设备已断开连接", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(fragment.getContext(), "无法断开设备连接", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(fragment.getContext(), "断开设备连接时出错", Toast.LENGTH_SHORT).show();
                }
            });

            // 设置移除按钮
            mBinding.tvRemoveBluetooth.setOnClickListener(view -> {
                try {
                    Method removeBondMethod = BluetoothDevice.class.getMethod("removeBond");
                    boolean removed = (boolean) removeBondMethod.invoke(finalConnectedDevice);
                    if (removed) {
                        saveList.remove(finalConnectedDevice);
                        bluetoothSaveListAdapter.notifyDataSetChanged();
                        connectList.remove(position);
                        bluetoothConnectListAdapter.notifyItemRemoved(position);
                        hideAllDetailViews();
                        Toast.makeText(fragment.getContext(), "设备已移除", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(fragment.getContext(), "无法移除设备", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(fragment.getContext(), "移除设备时出错", Toast.LENGTH_SHORT).show();
                }
            });

            // 设置开关按钮的点击事件
            mBinding.switchPhoneAudio.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    connectAudioProfile(finalConnectedDevice, BluetoothProfile.HEADSET);
                } else {
                    disconnectAudioProfile(finalConnectedDevice, BluetoothProfile.HEADSET);
                }
            });

            mBinding.switchMediaAudio.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    connectAudioProfile(finalConnectedDevice, BluetoothProfile.A2DP);
                } else {
                    disconnectAudioProfile(finalConnectedDevice, BluetoothProfile.A2DP);
                }
            });

            mBinding.switchBluetoothTethering.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    connectAudioProfile(finalConnectedDevice, BluetoothProfile.HEALTH);
                } else {
                    disconnectAudioProfile(finalConnectedDevice, BluetoothProfile.HEALTH);
                }
            });
        }
    }

    private boolean isAudioProfileConnected(BluetoothDevice device, int profile) {
        final boolean[] isConnected = {false};
        BluetoothProfile.ServiceListener serviceListener = new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                List<BluetoothDevice> connectedDevices = proxy.getConnectedDevices();
                if (connectedDevices.contains(device)) {
                    isConnected[0] = true;
                }
                bluetoothAdapter.closeProfileProxy(profile, proxy);
            }

            @Override
            public void onServiceDisconnected(int profile) {
                // 此处无需操作
            }
        };

        bluetoothAdapter.getProfileProxy(fragment.getContext(), serviceListener, profile);
        return isConnected[0];
    }

    private void connectAudioProfile(BluetoothDevice device, int profile) {
        BluetoothProfile.ServiceListener serviceListener = new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                try {
                    Method connectMethod = proxy.getClass().getMethod("connect", BluetoothDevice.class);
                    connectMethod.invoke(proxy, device);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                bluetoothAdapter.closeProfileProxy(profile, proxy);
            }

            @Override
            public void onServiceDisconnected(int profile) {

            }
        };
        bluetoothAdapter.getProfileProxy(fragment.getContext(), serviceListener, profile);
    }

    private void disconnectAudioProfile(BluetoothDevice device, int profile) {
        BluetoothProfile.ServiceListener serviceListener = new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                try {
                    Method disconnectMethod = proxy.getClass().getMethod("disconnect", BluetoothDevice.class);
                    disconnectMethod.invoke(proxy, device);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                bluetoothAdapter.closeProfileProxy(profile, proxy);
            }

            @Override
            public void onServiceDisconnected(int profile) {

            }
        };
        bluetoothAdapter.getProfileProxy(fragment.getContext(), serviceListener, profile);
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onValidItemClick(int position) {
        // 处理可用设备列表项的点击事件
        BluetoothDevice device = validList.get(position);
        Log.d("BluetoothPopup", "Valid device clicked: " + device.getName());

        // 设备配对
        Log.d("BluetoothPopup", "Attempting to bond with device: " + device.getName());
        device.createBond();
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onDeleteClick(int position) {
        Log.d("BluetoothPopup", "Saved device deleted: " + saveList.get(position));
        // 处理删除已配对设备的点击事件
        BluetoothDevice device = saveList.get(position);

        if (device != null) {
            try {
                Method removeBondMethod = BluetoothDevice.class.getMethod("removeBond");
                boolean removed = (boolean) removeBondMethod.invoke(device);
                if (removed) {
                    saveList.remove(position);
                    bluetoothSaveListAdapter.notifyItemRemoved(position);
                    Toast.makeText(fragment.getContext(), "设备已删除", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(fragment.getContext(), "无法删除设备", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(fragment.getContext(), "删除设备时出错", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void hideAllDetailViews() {
        mBinding.validDevice.setVisibility(View.GONE);
        mBinding.clBluetoothConnectMsg.setVisibility(View.GONE);
        mBinding.modifyName.setVisibility(View.GONE);
    }

    // 设置蓝牙名称
    @SuppressLint("MissingPermission")
    private void setBluetoothName(String newName) {
        String currentName = mBinding.tvBluetoothName.getText().toString();
        if (newName.isEmpty()) {
            Toast.makeText(fragment.getContext(), "名称不能为空", Toast.LENGTH_SHORT).show();
        } else if (newName.equals(currentName)) {
            Toast.makeText(fragment.getContext(), "名称与当前名称相同", Toast.LENGTH_SHORT).show();
        } else {
            if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.setName(newName);
                Log.d("BluetoothPopup", "Bluetooth name changed to: " + bluetoothAdapter.getName());
                Toast.makeText(fragment.getContext(), "蓝牙名称已更改为: " + newName, Toast.LENGTH_SHORT).show();
                mBinding.tvBluetoothName.setText(newName);
            } else {
                Toast.makeText(fragment.getContext(), "请先打开蓝牙", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 搜索蓝牙设备
    @SuppressLint("MissingPermission")
    private void startBluetoothDiscovery() {
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            // 显示加载动画
            mBinding.progressBar.setVisibility(View.VISIBLE);
            mBinding.tvSearchBluetoothCancel.setVisibility(View.VISIBLE);

            // 启动蓝牙搜索
            bluetoothAdapter.startDiscovery();

            // 注册广播接收器以获取搜索结果
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            fragment.getContext().registerReceiver(receiver, filter);

            // 显示可用设备视图
            hideAllDetailViews();
            mBinding.validDevice.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(fragment.getContext(), "请先打开蓝牙", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("MissingPermission")
    private void stopBluetoothDiscovery() {
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        mBinding.progressBar.setVisibility(View.GONE);
        mBinding.tvSearchBluetoothCancel.setVisibility(View.GONE);
        // Toast.makeText(fragment.getContext(), "蓝牙搜索已取消", Toast.LENGTH_SHORT).show();
    }

    // 蓝牙搜索结果的广播接收器
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 只显示未配对的设备
                if (device != null && device.getBondState() != BluetoothDevice.BOND_BONDED && !validList.contains(device)) {
                    validList.add(device);
                    bluetoothValidListAdapter.notifyDataSetChanged();
                    Log.d("BluetoothPopup", "Found device: " + device.getName());
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                // 隐藏加载动画
                mBinding.progressBar.setVisibility(View.GONE);
                mBinding.tvSearchBluetoothCancel.setVisibility(View.GONE);
                Log.d("BluetoothPopup", "Bluetooth discovery finished");
            }
        }
    };

    // 蓝牙配对成功的广播接收器
    private final BroadcastReceiver bondReceiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d("BluetoothPopup", "Broadcast received: " + action);
            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                Log.d("BluetoothPopup", "Bond state changed");
                final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
                final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
                if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (device != null) {
                        // 配对成功,添加到已配对设备列表
                        saveList.add(device);
                        bluetoothSaveListAdapter.notifyDataSetChanged();

                        // 自动连接设备
                        connectToDevice(device);

                        // 从可用设备列表中移除
                        validList.remove(device);
                        bluetoothValidListAdapter.notifyDataSetChanged();

                        Toast.makeText(fragment.getContext(), "配对成功", Toast.LENGTH_SHORT).show();
                        Log.d("BluetoothPopup", "Device paired successfully: " + device.getName());
                    }
                }
            }
        }
    };

    // 蓝牙状态变化的广播接收器
    private final BroadcastReceiver bluetoothStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                if (state == BluetoothAdapter.STATE_ON) {
                    // 蓝牙已打开,尝试自动连接已配对设备
                    autoConnectDevices();
                }
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        fragment.getContext().unregisterReceiver(receiver);
        fragment.getContext().unregisterReceiver(bondReceiver);
        fragment.getContext().unregisterReceiver(bluetoothStateReceiver);
        Log.d("BluetoothPopup", "Receiver unregistered");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值