700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > android 关闭蓝牙功能 android – 打开和关闭蓝牙?

android 关闭蓝牙功能 android – 打开和关闭蓝牙?

时间:2022-02-04 03:58:16

相关推荐

android 关闭蓝牙功能 android  – 打开和关闭蓝牙?

你需要

在您的清单文件中,以及变量如:

private final integer REQUEST_ENABLE_BT = 1;

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

boolean hasBluetooth = (mBluetoothAdapter == null);

所以在你的OnCreate中你可以做类似的事情:

final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton);

togglebutton.setOnClickListener(new OnClickListener()

{

public void onClick(View v)

{

// Perform action on clicks

if (togglebutton.isChecked())

{

if (hasBluetooth && !mBluetoothAdapter.isEnabled())

{

// prompt the user to turn BlueTooth on

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

}

else

{

if (hasBluetooth && mBluetoothAdapter.isEnabled())

{

// you should really prompt the user for permission to turn

// the BlueTooth off as well, e.g., with a Dialog

boolean isDisabling = mBluetoothAdapter.disable();

if (!isDisabling)

{

// an immediate error occurred - perhaps the bluetooth is already off?

}

}

}

}

});

用户对“转动蓝牙开启”提示的响应被捕获

protected void onActivityResult (int requestCode, int resultCode, Intent data)

{

if ((requestCode == REQUEST_ENABLE_BT) && (resultCode == RESULT_OK))

{

boolean isEnabling = mBluetoothAdapter.enable();

if (!isEnabling)

{

// an immediate error occurred - perhaps the bluetooth is already on?

}

else if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_ON)

{

// the system, in the background, is trying to turn the Bluetooth on

// while your activity carries on going without waiting for it to finish;

// of course, you could listen for it to finish yourself - eg, using a

// ProgressDialog that checked mBluetoothAdapter.getState() every x

// milliseconds and reported when it became STATE_ON (or STATE_OFF, if the

// system failed to start the Bluetooth.)

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。