开启和关闭切换蓝牙? [英] Toggling Bluetooth on and off?
本文介绍了开启和关闭切换蓝牙?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个简单的教程或剂量人有code切换蓝牙和关闭在Eclipse的建筑采用拨动式按键为Android?
Is there a simple tutorial or dose anyone have code to toggle Bluetooth on and off using a Toggle-button in eclipse building for android?
如果有人能帮助那将是极大的AP preciated。
If anyone can help that will be greatly appreciated.
- 谢谢提前。
推荐答案
您将需要
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
在你的清单文件,并像变量:
in your manifest file, and variables like:
private final integer REQUEST_ENABLE_BT = 1;
和
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean hasBluetooth = (mBluetoothAdapter == null);
让你的OnCreate中,你可以这样做:
so that in your OnCreate you can do something like:
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?
}
}
}
}
});
在用户响应打开蓝牙提示陷入
where the user response to the "turn bluetooth on" prompt is caught in
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.)
}
}
}
这篇关于开启和关闭切换蓝牙?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文