简体   繁体   中英

Discovering Bluetooth Sample

I'm learning about bluetooth apps and the first sample I've come across, seems to be well documented but I cannot for the life of me get it to reproduce the "Search Devices" part, any help would be greatly appreciated.

 public class MainActivity extends AppCompatActivity {

private Button onBtn, offBtn, listBtn, findBtn;
private TextView text;
private ListView myListView;

// Bluetooth global variables
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter myBluetoothAdapter;
public Set<BluetoothDevice> pairedDevices;
private ArrayAdapter<String> BTArrayAdapter;
@Override


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if(myBluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
                    Toast.LENGTH_LONG).show();
        }
        else
        {

            text = (TextView) findViewById(R.id.text);
            onBtn = (Button)findViewById(R.id.turnOn);
            offBtn = (Button)findViewById(R.id.turnOff);
            listBtn = (Button)findViewById(R.id.paired);
            findBtn = (Button)findViewById(R.id.search);

            myListView = (ListView)findViewById(R.id.listView1);

            // create the arrayAdapter that contains the bluetooth d evices, and set it to the ListView
            BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
            myListView.setAdapter(BTArrayAdapter);

            myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    String selectedFromList =(String) (myListView.getItemAtPosition(i));
                    Toast.makeText(getApplicationContext(),"Bluetooth remote device : " + selectedFromList,
                            Toast.LENGTH_LONG).show();
                }
            });



        }

    } // onCreate


public void on(View view){
    if (!myBluetoothAdapter.isEnabled()) {
        Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);

        Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
                Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(getApplicationContext(),"Bluetooth is already on",
                Toast.LENGTH_LONG).show();
    }
}

public void off(View view){
    myBluetoothAdapter.disable();
    text.setText("Status: Disconnected");

    Toast.makeText(getApplicationContext(),"Bluetooth turned off",
            Toast.LENGTH_LONG).show();
}

public void list(View view){
    // get paired devices
    pairedDevices = myBluetoothAdapter.getBondedDevices();

    // put it's one to the adapter
    for(BluetoothDevice device : pairedDevices)
        BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());

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

}

final BroadcastReceiver bReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // add the name and the MAC address of the object to the arrayAdapter
            BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            BTArrayAdapter.notifyDataSetChanged();
        }
    }
};

public void find(View view) {
    if (myBluetoothAdapter.isDiscovering()) {
        // the button is pressed when it discovers, so cancel the discovery
        Toast.makeText(getApplicationContext(),"Bluetooth cancelled discovery" ,
                Toast.LENGTH_LONG).show();
        myBluetoothAdapter.cancelDiscovery();
    } else {
        BTArrayAdapter.clear();
        Toast.makeText(getApplicationContext(),"Bluetooth discovery started" ,
                Toast.LENGTH_LONG).show();

        myBluetoothAdapter.startDiscovery();

        registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
    }

}

@Override
protected void onDestroy() {
    super.onDestroy();
}

}

Using a Oneplus3 & 2 to test this, and neither device can find the other, unless already paired with each other. I want to see if I can search and get the device to populate in a list like the paired devices already do.

If there's anything else you need me to put in let me know, hope you don't mind taking the time to help out with this one!

You need to add one of the following permission to your Manifest.xml to find devices:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

or

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

If you are working on API 23 and higher you must ensure this permission is granted because it is a dangerous level permission.

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app

See this guide to request permission(s).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM