Bluetooth on Android: StartDiscovery not working. Cannot scan devices

≯℡__Kan透↙ 提交于 2020-01-14 06:51:08

问题


I am new to android and i am making an application with bluetooth functionalities. I am able to set the bluetooth adaptor, an fetch my own device information, but i could not use startdiscovery to discover bluetooth devices. When i start a scan it does nothing.

i am using an onclicklistner to start a scan:

  bt.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {
               if (!(bluetooth.isEnabled())) {
                   status = "Bluetooth is not Enabled.";
                   Toast.makeText(AddUser.this, status, Toast.LENGTH_LONG).show();
                   Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);

                }
                else
                {

                    scand();
                }

           }

Here is the onActivityResult function which i have put just after the "public void onCreate" function:

 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    System.out.println(resultCode);
    if (resultCode ==  RESULT_CANCELED) {
        status="Error Enabling bluetooth";
        Toast.makeText(AddUser.this, status, Toast.LENGTH_LONG).show();
    } else {

            scand();
    }



}

This is my scand function, in which i am callng startdiscovery:

    private void scand()
{



   bluetooth.startDiscovery(); 
   Log.d("itmes", ""+items.size());
   item1 = new String[items.size()];
   item1 = items.toArray(item1);
   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   builder.setTitle("Choose a device");
   builder.setItems(item1, new DialogInterface.OnClickListener() {

       public void onClick(DialogInterface dialog, int item) {
            Toast.makeText(getApplicationContext(), item1[item], Toast.LENGTH_SHORT).show();

       }

    });

    AlertDialog alert = builder.create();

    alert.show();

}

This is the broadcastReceiver:

 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) 
            {
                   Log.e("br", "--- device found ---");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

               items.add(device.getName());
            }
          }
        };

In the Above code for broadcastreceiver, i am trying to put the found device name in a string ArrayList "items".

I am registering broadcastreceiver inside the oncreate functon like this:

filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
   registerReceiver(mReceiver, filter);

i have set bluetooth permissions in the androidmanifest file. In the scand function above, it is suppose to show the list of discovered devices, but it is displaying an empty dialog with just the title. Please tell me how to use startdiscovery and broadcastreceiver properly to display the result in the alertdialog.


回答1:


The startDiscovery() is asynchronous you will not receive the result right after the call. Move the code to show the dialog to a function let say public void showScanResult() and call that in your onReceive.




回答2:


Check you have

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

in your manifest.

See https://developer.android.com/reference/android/bluetooth/BluetoothDevice#ACTION_FOUND




回答3:


   discovery()
       {
          IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
         this.registerReceiver(mReceiver, filter);
        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);

        // If we're already discovering, stop it
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // Request discover from BluetoothAdapter
        mBluetoothAdapter.startDiscovery();

}

Broadcast receiver:

  private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        try {
            Broadcast=true;
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                // If it's already paired, skip it, because it's been listed
                // already
                if (device.getBondState() !=BluetoothDevice.BOND_BONDED)    {

                    near_device.add(device.getAddress());

                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                scanResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

};

 scanresult()
    {

            mBluetoothAdapter.cancelDiscovery();
            receiverCheck = false;
            // Unregister broadcast listeners
            Home.this.unregisterReceiver(mReceiver);
          // near device arraylist contain all device mac address
    }



回答4:


Well, in my opinion when you set the array item1 as the contents to be shown in the AlertDialog you are telling that Dialog to show the items that are in the array in THAT moment (an empty array) so you will see no elements.

I am not sure that you can, after doing that, update the contents of item1 array and expect the AlertDialog to be refreshed. I don't think this is working like that (But I never tried it, anyway).

I did something similar into my application using a ListView and an Adapter, so when you add an item via the adapter the ListView is refreshed (you have to use adapter.notifyDataSetChanged() anyway) :

protected ArrayList<BluetoothDevice> foundDevices 
                      = new ArrayList<BluetoothDevice>();
private ListView foundDevicesListView;
private ArrayAdapter<BluetoothDevice> adapter;

foundDevicesListView = (ListView) findViewById(R.id.foundDevicesListView);

adapter = new ArrayAdapter<BluetoothDevice>(this,
            android.R.layout.simple_list_item_1, foundDevices);
foundDevicesListView.setAdapter(adapter);
//
//  Initialization, etc ....


    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a new device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE));
                if (!foundDevices.contains(device)) {
                    foundDevices.add(device);
                    adapter.notifyDataSetChanged();
                }
            }

            // When discovery cycle finished
            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if(foundDevices==null || foundDevices.isEmpty()){
                    // Show not devices found message
                }
            }
        } 


来源:https://stackoverflow.com/questions/16184420/bluetooth-on-android-startdiscovery-not-working-cannot-scan-devices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!