首页 > 解决方案 > 在列表视图 [Android Studio] 中更新附近未配对的蓝牙设备列表

问题描述

注意:我对 android studio (java) 完全陌生,这是我的第一个项目。

我正在尝试扫描所有(配对和未配对的)蓝牙设备并在应用程序屏幕上显示这些设备的列表。

到目前为止,我已经成功获得了一份清单,但以下问题仍然存在:

1) 随着新的未配对设备被扫描,较早扫描的设备在显示列表中作为副本重复出现。

2) 如果我关闭设备中的发现功能,则列表不会更新并继续在列表中显示已关闭(不再可用)的设备。

问题:每次设备可用或不可用时,蓝牙设备列表都不会正确更新。

我尝试在更新之前清除我的数组列表。似乎不起作用。另外,我知道在 stackoverflow 和其他网站上有很多资源,这些资源涵盖了获取附近蓝牙设备列表的类似主题。我已经关注了其中的多个并编写了我的代码,但找不到任何可以解决这个“列表更新”问题的东西。

我正在分享当前的代码和结果。请建议编辑/添加。

感谢您的时间和帮助。

主要活动类代码


public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_ENABLE_BT = 1;                         //Enable bluetooth request variable
    private static final int REQUEST_DISCOVERABILITY = 1 ;                  //Make bluetooth discoverable request variable

    private BluetoothAdapter btAdapter;                                     //Define bluetooth adapter variable

    ArrayList<String> deviceList = new ArrayList<>();                       //Store paired devices list
    ArrayList<String> newDevices = new ArrayList<>();                       //Store available devices list
    ArrayList<String> allDevices = new ArrayList<>();                       //Store all devices for display on screen

    ListView btList;                                                        //Define list UI item



    @Override
    protected void onCreate(Bundle savedInstanceState) {                    //On activity creation do the following


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);                             //Pre-written -- to set layout as screen UI


        btList = (ListView)findViewById(R.id.list1);                        //Set list variable to UI item in layout


        btAdapter = BluetoothAdapter.getDefaultAdapter();                   //Initialize adapter


        if(allDevices != null){

            allDevices.clear();                                             //Clear array to display fresh list
        }



        int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},   //Ask for permission to turn on location
                MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);



    }



    public void btOn(View view){                                           //Bluetooth On event

        if (btAdapter != null) {

            if (!btAdapter.isEnabled()) {                                  //Enable bluetooth if not enables already
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
            else{                                                          //If already enabled display list of paired devices

                pairedList();

            }
        }

    }



    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_ENABLE_BT) {

            if (resultCode == RESULT_OK) {

                pairedList();                                              //If user has enabled bluetooth, show list of paired devices

            }

        }
    }


    public void discoverOn(){                                              //Method for setting bluetooth on discoverable mode
                                                                           //for 5 minutes
        Intent discoverableIntent =
                new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivityForResult(discoverableIntent, REQUEST_DISCOVERABILITY);


    }




    public void scanNewDevices(View view){                                  //Scan for unpaired available bluetooth devices when "scan button" is clicked

        discoverOn();                                                       //Set bluetooth to discoverable

        if (btAdapter.isDiscovering()) {
                                                                            //Bluetooth is already in mode discovery mode, we cancel to restart it again
            btAdapter.cancelDiscovery();
        }
        btAdapter.startDiscovery();                                         //Start scanning

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

        registerReceiver(receiver, filter);


    }






    public void pairedList(){                                                //Method gets list of paired devices

        Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();

        if (deviceList != null) {                                            //Clear older list items
            deviceList.clear();
        }

        if(pairedDevices != null) {
            for (BluetoothDevice bt : pairedDevices) {

                deviceList.add(bt.getName() + '\n' + bt.getAddress());      //Add current items
            }
        }


        Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();

        allDevices.addAll(deviceList);                                      //Update final display list

        showList();                                                         //Display list on screen

    }


                                                                            //Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                                                                            //Discovery has found a device. Get the BluetoothDevice
                                                                            //object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);



                if(newDevices != null){

                    newDevices.clear();                                     //Clear earlier list

                }


                if (device != null ) {

                    newDevices.add(device.getName() + '\n' + device.getAddress());

                    allDevices.addAll(newDevices);                          //Update new devices in final display list

                    showList();                                             //Display list
                }

            }
        }
    };

    @Override
    protected void onDestroy() {                                           //When application is closed,
        super.onDestroy();
                                                                           //Unregister the ACTION_FOUND receiver.
        unregisterReceiver(receiver);
    }



    public void showList(){                                                 //Method to set device list to ListView UI

        final ArrayAdapter<String> adapter = new  ArrayAdapter<>(this,android.R.layout.simple_list_item_1, allDevices);

        btList.setAdapter(adapter);

    }

}


activity_main.xml 代码:了解布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="96dp"
        android:layout_marginLeft="96dp"
        android:layout_marginTop="56dp"
        android:onClick="btOn"
        android:text="@string/btbutton"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ListView
        android:id="@+id/list1"
        android:layout_width="305dp"
        android:layout_height="500dp"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="204dp"
        android:layout_marginEnd="32dp"
        android:layout_marginRight="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="104dp"
        android:layout_marginLeft="104dp"
        android:layout_marginTop="124dp"
        android:onClick="scanNewDevices"
        android:text="@string/button2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

当前结果

重复的设备名称,如果我关闭任何这些设备,它们仍会显示在列表中。

重复的设备名称,如果我关闭这些设备中的任何一个,它们仍会显示在列表中

标签: javaandroidandroid-studiobluetooth

解决方案


推荐阅读