Android上的蓝牙:StartDiscovery无法正常工作。无法扫描设备

时间:2013-04-24 05:59:03

标签: android bluetooth

我是Android的新手,我正在制作一个具有蓝牙功能的应用程序。我能够设置蓝牙适配器,获取我自己的设备信息,但我无法使用startdiscovery来发现蓝牙设备。当我开始扫描时,它什么也没做。

我正在使用onclicklistner开始扫描:

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

           }

这是我在“public void onCreate”函数之后放置的onActivityResult函数:

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



}

这是我的scand函数,其中我是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();

}

这是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());
            }
          }
        };

在broadcastreceiver的Above代码中,我试图将找到的设备名称放在字符串ArrayList“items”中。

我正在oncreate functon中注册broadcastreceiver,如下所示:

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

我在androidmanifest文件中设置了蓝牙权限。在上面的scand函数中,它假设显示已发现设备的列表,但它显示一个只有标题的空对话框。请告诉我如何正确使用startdiscovery和broadcastreceiver在alertdialog中显示结果。

4 个答案:

答案 0 :(得分:2)

检查你有

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
在你的清单中

请参阅 https://developer.android.com/reference/android/bluetooth/BluetoothDevice#ACTION_FOUND

答案 1 :(得分:1)

startDiscovery()是异步的,您不会在通话后立即收到结果。移动代码将对话框显示给一个函数让我们说public void showScanResult()并在你的onReceive中调用它。

答案 2 :(得分:1)

   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();

}

广播接收器:

  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
    }

答案 3 :(得分:0)

嗯,在我看来,当你将数组item1设置为要在AlertDialog中显示的内容时,你告诉Dialog在那个时刻显示数组中的项目(一个空数组)所以你会看到没有元件。

我不确定您是否可以在执行此操作后更新item1数组的内容并期望刷新AlertDialog。我认为这不是那样的(但我从来没有尝试过它)。

我使用ListView和Adapter在我的应用程序中做了类似的事情,所以当你通过适配器添加一个项目时,ListView会被刷新(你必须使用adapter.notifyDataSetChanged()):

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
                }
            }
        }