我想启用蓝牙并在一秒钟后禁用它。但是我不知道该怎么做,我已经尝试过了,但是它什么也没做,只是启用了蓝牙。我这样做的原因是因为我实际上想禁用蓝牙。但是它仅在您还使用应用程序本身中的Intent启用了*的情况下才有效,否则它会强制关闭(如果已通过通知栏启用)
我正在使用此代码来启用/禁用蓝牙
public void optimize(View view) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}else{
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}else{
mBluetoothAdapter.disable();
}
}
我现在使用的代码
public void optimize(View view) {
final BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}else{
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
{Thread mythread = new Thread() {
public void run()
{
try
{
sleep(1000);
}
catch (Exception e)
{
}
finally
{
BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.disable();
}
}
};
}
}
}
试试看,使用Android处理程序的postdelayed()。
在指定的时间(以毫秒为单位)后,它将在run()块内执行代码。
public void optimize(View view) {
final BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}else{
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
// Instead of run Thread , use Handler's Postdelayed method as,
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
// Runs this after 1 second
BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.disable();
}
}, 1000); // After 1 second it executes code inside run()
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句