我有一个带有按钮的应用程序,用于打开和关闭BT。我在那里有以下代码;
public void buttonFlip(View view) {
flipBT();
buttonText(view);
}
public void buttonText(View view) {
Button buttonText = (Button) findViewById(R.id.button1);
if (mBluetoothAdapter.isEnabled() || (mBluetoothAdapter.a)) {
buttonText.setText(R.string.bluetooth_on);
} else {
buttonText.setText(R.string.bluetooth_off);
}
}
private void flipBT() {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
} else {
mBluetoothAdapter.enable();
}
}
我正在调用按钮Flip,它会翻转BT状态,然后调用ButtonText,它应该更新UI。但是,我遇到的问题是,BT打开需要几秒钟 - 在这几秒钟内,BT状态未启用,使我的按钮说蓝牙关闭,即使它将在2秒内打开。
我在BluetoothAdapter android文档中找到了STATE_CONNECTING
常量,但是......我根本就不知道如何使用它,成为新手和所有人。
所以,我有两个问题:
答案 0 :(得分:173)
您需要注册BroadcastReceiver
以收听BluetoothAdapter
状态的任何变化:
作为Activity
中的私有实例变量(或在单独的类文件中...您喜欢的任何一个):
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
setButtonText("Bluetooth off");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
setButtonText("Turning Bluetooth off...");
break;
case BluetoothAdapter.STATE_ON:
setButtonText("Bluetooth on");
break;
case BluetoothAdapter.STATE_TURNING_ON:
setButtonText("Turning Bluetooth on...");
break;
}
}
}
};
请注意,这假设您的Activity
实施的方法setButtonText(String text)
会相应地更改Button
的文字。
然后在Activity
中,注册并取消注册BroadcastReceiver
,如下所示,
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* ... */
// Register for broadcasts on BluetoothAdapter state change
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
/* ... */
// Unregister broadcast listeners
unregisterReceiver(mReceiver);
}
答案 1 :(得分:-1)
public void discoverBluetoothDevices(View view)
{
if (bluetoothAdapter!=null)
bluetoothAdapter.startDiscovery();
Toast.makeText(this,"Start Discovery"+bluetoothAdapter.startDiscovery(),Toast.LENGTH_SHORT).show();
}