检查是否使用Android应用程序启用蓝牙
我想检查在使用Android应用程序的设备中是否启用了蓝牙。 我使用了.isEnabled方法。但是有一个错误。我发现(通过注释行)错误在.isEnabled方法中。你能帮我解决这个问题吗?检查是否使用Android应用程序启用蓝牙
final BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String status = "Bluetooth";
if(bluetooth != null) {
if (bluetooth.isEnabled()) {
String mydeviceaddress = bluetooth.getAddress();
String mydevicename = bluetooth.getName();
status = ("Address "+ mydeviceaddress + " Name" + mydevicename);
Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show();
} else {
status = ("Bluetooth not enabled");
Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show();
}
}
}
试试这个。
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device does not support Bluetooth
} else {
if (!bluetoothAdapter.isEnabled()) {
// Bluetooth is not enabled
}
}
在
AndroidManifest.xml File
添加
<uses-permission android:name="android.permission.BLUETOOTH" />
这工作最适合我:
/**
* Check for Bluetooth.
* @return True if Bluetooth is available.
*/
public static boolean isBluetoothAvailable() {
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return (bluetoothAdapter != null && bluetoothAdapter.isEnabled());
}
感谢您以最佳方式分享它... #makesense – CoDe
只有一件事,为什么该方法需要一个Context对象,真的使用它吗? – hmartinezd
@hmartinezd好眼睛,现在已经修好了。 –
为什么不干脆:
...
return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled();
贾里德Burrows的答案似乎是正确的一个,但是我不得不一个dd在开始工作之前添加一个。我必须检查蓝牙状态。
public static boolean isBluetoothAvailable() {
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return (bluetoothAdapter != null &&
bluetoothAdapter.isEnabled() &&
bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON);
}
我刚试过。但是这也不起作用:( – Saku
@Saku有什么错误?更新你的文章,并把错误的详细信息 – Bishan
'强制关闭'出现由于模拟器不支持蓝牙我试着在一个实际的选项卡。 t给出明确的例外或错误信息 – Saku