Discoverydevice.java和activity_discoverydevice.xml

一、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")
    @Override
    protected 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")
            @Override
            public 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")
        @Override
        public 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")
            @Override
            public 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();
                    }
                }
            }

            @Override
            public 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();
        }
    }

    @Override
    protected 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">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/button_style"
        android:text="扫描设备"
        android:textColor="#000000" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50px"
        android:text="附近设备" />

    <ListView
        android:id="@+id/listview2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20px"
        android:background="@drawable/listview_style1" /> 
</LinearLayout>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值