在Android上发现蓝牙设备

时间:2016-02-14 14:32:44

标签: android bluetooth

我已经搜索过并尽力而为,但我无法让它发挥作用。从我见过的所有例子来看,我似乎都在做正确的事,但也许我错过了一些东西。

我正在尝试在Android上发现蓝牙设备,并且一直在关注Android开发者页面上的指南:http://developer.android.com/guide/topics/connectivity/bluetooth.html 我可以在应用启动时启用BT并获取设备的名称和地址。但是,我看不到附近其他设备的名称(应该显示为吐司)。有趣的是,当我在启动应用程序之前启用BT时,它实际上做了我想要的并显示了附近设备的名称。

以下是代码:

public class MainActivity extends AppCompatActivity {

TextView mTextView;
BluetoothAdapter mBluetoothAdapter;

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

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    final String status;

    // Check BT support
    if (mBluetoothAdapter == null){
        // Device does not support BT
        status = "Your device does not support Bluetooth";
    }
    else {
        String myAddress = mBluetoothAdapter.getAddress();
        String myName = mBluetoothAdapter.getName();
        status = myName + ": " + myAddress;
    }

    mTextView = (TextView)findViewById(R.id.textView);

    // If BT is enabled before app start, discover devices
    // This is where things work, for some reason
    if (mBluetoothAdapter.isEnabled()){
        mTextView.setText(status);
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBroadcastReceiver, filter);
        getBTdevices();
    }

    // If BT is not enabled, enable it and look for devices
    else{
        mTextView.setText(status);
        mBluetoothAdapter.enable();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBroadcastReceiver, filter);
        getBTdevices();
    }
}

protected void getBTdevices(){

    // Stop discovery and start
    if (mBluetoothAdapter.isDiscovering()){
        mBluetoothAdapter.cancelDiscovery();
    }
    mBluetoothAdapter.startDiscovery();

}

private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        TextView textView = (TextView)findViewById(R.id.textView2);
        textView.setText("Start");
        String action = intent.getAction();
        // If device is found
        if (BluetoothDevice.ACTION_FOUND.equals(action)){
            // Get BT device from intent
            textView.setText("Device found");
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Toast.makeText(context, "Device found: "+ device.getName(), Toast.LENGTH_LONG).show();
            System.out.println("Discovered!");
        }
    }
};

protected void onDestroy(){
    super.onDestroy();
    if (mBluetoothAdapter.isDiscovering()){
        mBluetoothAdapter.cancelDiscovery();
    }
    unregisterReceiver(mBroadcastReceiver);

}
}

我真的很感激一些帮助,我不知道还能做些什么。

编辑:忘记提及,我在清单中设置了BLUETOOTH和BLUETOOTH_ADMIN权限。

0 个答案:

没有答案