1
我正在使用BluetoothAdapter.getScanMode()
來檢查設備的藍牙是否設置爲可發現。但是,如果藍牙關閉,然後getScanMode()
返回SCAN_MODE_NONE
,它不告訴我它是否可發現。如何檢查藍牙即使在關閉時也能發現?檢查藍牙關閉時是否可以發現Android藍牙?
我正在使用BluetoothAdapter.getScanMode()
來檢查設備的藍牙是否設置爲可發現。但是,如果藍牙關閉,然後getScanMode()
返回SCAN_MODE_NONE
,它不告訴我它是否可發現。如何檢查藍牙即使在關閉時也能發現?檢查藍牙關閉時是否可以發現Android藍牙?
要確定藍牙是否可發現,我會檢查適配器上的當前狀態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;
}
}
}