Finding Android Bluetooth Paired Devices

前端 未结 3 1810
谎友^
谎友^ 2020-12-19 17:23

I\'m trying to create an image button that, when pressed, presents the users a list of Paired Bluetooth devices to connect to.

However, I get \"Set cannot be resolve

3条回答
  •  天涯浪人
    2020-12-19 17:49

    For 1) Well if you haven't done so , add

    > import java.util.Set;

    in your import statements . This will resolve "Set" error.

    For 2) Declare and initialize

    mArrayAdapter

    For example in your Activity do :

    private ArrayAdapter mArrayAdapter;
    

    and then on onCreate:

     mArrayAdapter= new ArrayAdapter(this, );
    

    which should then be added to a ListView

    // Find and set up the ListView for newly discovered devices

       ListView newDevicesListView = (ListView)
     findViewById(R.id.);
             newDevicesListView.setAdapter(mArrayAdapter);
    
     newDevicesListView.setOnItemClickListener(mDeviceClickListener);
    

    Refer to Bluetooth Chat example from Android examples. It should help you get going with the Bluetooth api's


    Update on comment :

    If you look closely on BluetoothChat.java file in BT example, you'll see this

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if(D) Log.d(TAG, "onActivityResult " + resultCode);
            switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    // Get the device MAC address
                    String address = data.getExtras()
                                         .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    // Get the BLuetoothDevice object
                    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                    // Attempt to connect to the device
                    mChatService.connect(device);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                } else {
                    // User did not enable Bluetooth or an error occured
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    

    Watch this line :

     // Attempt to connect to the device
     mChatService.connect(device);
    

    This function connects to bluetooth device. First time it'll ask you to pair it automatically. Once paired, next time it'll auto connect to the bluetooth device.

提交回复
热议问题