蓝牙关闭时检查Android蓝牙是否可被发现?

时间:2015-05-25 00:53:33

标签: android bluetooth

我正在使用BluetoothAdapter.getScanMode()来检查设备的蓝牙是否设置为可发现。但是,如果蓝牙已关闭,则getScanMode()会返回SCAN_MODE_NONE,这不会告诉我它是否可被发现。如果蓝牙即使关闭也能检查蓝牙是否可被发现?

1 个答案:

答案 0 :(得分:0)

要确定蓝牙是否可被发现,我会检查适配器上的当前状态getState()。

MainActivity getState();

public class MainActivity extends AppCompatActivity {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (!BluetoothConnection.canDeviceConnectViaBluetooth(bluetoothAdapter, this)) {
            Toast.makeText(this, "Not Compatible", Toast.LENGTH_SHORT).show();
        } else {
            if (BluetoothConnection.isBluetoothAdapterEnabled(bluetoothAdapter, this)) {
                int isBlueToothDiscoverable = bluetoothAdapter.getState();
                switch (isBlueToothDiscoverable) {
                    case BluetoothAdapter.STATE_OFF:
                        Toast.makeText(this, "STATE_OFF", Toast.LENGTH_SHORT).show(); // Not discoverable 
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        Toast.makeText(this, "STATE_TURNING_ON", Toast.LENGTH_SHORT).show();  // Maybe discoverable 
                        break;
                    case BluetoothAdapter.STATE_ON:
                        Toast.makeText(this, "STATE_ON", Toast.LENGTH_SHORT).show();  // Discoverable 
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        Toast.makeText(this, "STATE_TURNING_OFF", Toast.LENGTH_SHORT).show(); // Not discoverable 
                        break;
                    default:
                        break;
                }
            }
        }
    }
}

检查设备是否兼容蓝牙

public class BluetoothConnection {
    public final static int REQUEST_ENABLE_BT = 1;

    public static boolean canDeviceConnectViaBluetooth(BluetoothAdapter bluetoothAdapter, Activity activity) {
        if (bluetoothAdapter == null) {
            Log.e("DEVICE_COMPATIBLE", "FALSE");
            return false;
        }
        return true;
    }

    public static boolean isBluetoothAdapterEnabled(BluetoothAdapter bluetoothAdapter, Activity activity) {
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            Log.e("IS_BLUETOOTH_ON", "FALSE");
            return false;
        } else {
            return true;
        }
    }
}