安卓蓝牙应用无法发现其他设备

3
我是一个Android的初学者,尝试了一个叫Bluetoothchat的演示代码,链接在https://developer.android.com/samples/BluetoothChat/index.html。但它在我的手机上(Nexus 5, Android 6.0.1)运行不好。完整的包在github上,链接在https://github.com/googlesamples/android-BluetoothChat。我没有改变演示中的任何东西。使用的是Android Studio 2.1.2。
它不能发现其他的蓝牙设备(iPad和黑莓)。设备的可见性已经打开。如果我在Nexus 5上使用默认的蓝牙发现功能,这两个设备会显示在列表中。
我还尝试了一些其他关于蓝牙发现应用的演示,但它们在我的手机上也无法工作。我知道如何查找设备的基本思路,但找不到为什么它不能正常工作的原因。
Bluetoothchat中相关的代码在这里:
基本设置
    mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
    // Find and set up the ListView for newly discovered devices
    ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
    newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
    newDevicesListView.setOnItemClickListener(mDeviceClickListener);

    // Register for broadcasts when a device is discovered
    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);

    // Get the local Bluetooth adapter
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();

点击“扫描”按钮以扫描设备

    // Initialize the button to perform device discovery
    Button scanButton = (Button) findViewById(R.id.button_scan);
    scanButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            doDiscovery();
            v.setVisibility(View.GONE);
        }
    });

    // Initialize array adapters. 
    // one for newly discovered devices

发现部分
/**
 * Start device discover with the BluetoothAdapter
 */
private void doDiscovery() {
    Log.d(TAG, "doDiscovery()");

    // Indicate scanning in the title
    setProgressBarIndeterminateVisibility(true);
    setTitle(R.string.scanning);

    // Turn on sub-title for new devices
    findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

    // If we're already discovering, stop it
    if (mBtAdapter.isDiscovering()) {
        mBtAdapter.cancelDiscovery();
    }

    // Request discover from BluetoothAdapter
    mBtAdapter.startDiscovery();
}

广播接收器
/**
 * The BroadcastReceiver that listens for discovered devices and changes the title when
 * discovery is finished
 */
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    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);
            // If it's already paired, skip it, because it's been listed already
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
            // When discovery is finished, change the Activity title
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            setProgressBarIndeterminateVisibility(false);
            setTitle(R.string.select_device);
            if (mNewDevicesArrayAdapter.getCount() == 0) {
                String noDevices = getResources().getText(R.string.none_found).toString();
                mNewDevicesArrayAdapter.add(noDevices);
            }
        }
    }
};

销毁部分

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

    // Make sure we're not doing discovery anymore
    if (mBtAdapter != null) {
        mBtAdapter.cancelDiscovery();
    }

    // Unregister broadcast listeners
    this.unregisterReceiver(mReceiver);
}

有人能帮我吗?先谢谢了!


我可以确认我的Nexus 6P也出现了这个问题。我添加了一个日志条目来查看哪些操作会触发BroadcastReciever,只有“DISCOVERY_FINISHED”操作被传递过来。 - ChronoFish
请参考此问题的答案:https://dev59.com/IFsW5IYBdhLWcg3wdW-T - ChronoFish
1个回答

2
确保您已将这些权限添加到您的Android清单中。"
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

如果不是自动请求,请确保您请求ACCESS_COARSE_LOCATION:

最初的回答:

    // Handling permissions.
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Permission is not granted
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)) {

            // Not to annoy user.
            Toast.makeText(this, "Permission must be granted to use the app.", Toast.LENGTH_SHORT).show();
        } else {

            // Request permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_PERMISSION_BLUETOOTH);
        }
    } else {
        // Permission has already been granted.
        Toast.makeText(this, "Permission already granted.", Toast.LENGTH_SHORT).show();
    }

并指定用户接受/拒绝请求后应该发生什么:

最初的回答

@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String permissions[], @NonNull int[] grantResults) {
    switch (requestCode) {
        case REQUEST_PERMISSION_BLUETOOTH: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(this, "Permission granted.", Toast.LENGTH_SHORT).show();

                // Permission granted.
            } else {
                Toast.makeText(this, "Permission must be granted to use the application.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接