我正在开发蓝牙应用程序。在我的应用程序中,我有以下代码。当蓝牙关闭意味着我的else语句在蓝牙上切换,发现设备列表(它工作正常)否则如果语句将运行并获取设备列表。
My problem is "if condition is runnning but it doesn't discover the devices"
。任何人都可以建议解决方案。
if (btAdapter.isEnabled()) {
registerReceiver(ActionFoundReceiver, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
btAdapter.startDiscovery();
} else {
Intent i1 = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(i1);
new java.util.Timer().schedule(new java.util.TimerTask() {
@Override
public void run() {
registerReceiver(ActionFoundReceiver, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
btAdapter.startDiscovery();
}
}, 5000);
}
//接收器检测设备代码
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
items += device.getName() + ",";
}
Toast.makeText(getApplicationContext(), items, Toast.LENGTH_LONG)
.show();
}
};
答案 0 :(得分:1)
我想这里正是你需要的。
http://developer.android.com/guide/topics/wireless/bluetooth.html#FindingDevices
http://developer.android.com/guide/topics/wireless/bluetooth.html#DiscoveringDevices
关于在不询问用户的情况下启用蓝牙,以下是该文档所说的内容:
Bluetooth should never be enabled without direct user consent. If you
want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.
但如果你真的想这样做,就有办法:
BluetoothAdapter.enable()
您可以在不询问用户的情况下调用此方法
为了使enable()有效,您必须在Android Manifest文件中添加权限
“android.permission.BLUETOOTH_ADMIN”
试试吧,
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));