【发布时间】:2016-12-18 05:07:39
【问题描述】:
我有两部 Android 手机。我想通过蓝牙在它们之间建立自动连接。例如,
我的安卓手机与另一个蓝牙配对。当我把这些手机放在一起时,它们需要检测蓝牙设备,并自动连接到选定的安卓手机(已知地址/MAC/之前配对)。我不需要再次连接它。我希望在我的 Android 应用程序中实现这种连接。
我谷歌并找到了一些相关的参考,但他们还没有解决问题。我认为我需要创建一个线程/服务以在蓝牙处于范围内时自动连接它们。但是,我无法实现它。如果您有好的解决方案,请告诉我。谢谢
Automatically connect to paired bluetooth device when in range
Find already paired bluetooth devices automatically, when they are in range
/**
* The BroadcastReceiver that listens for discovered devices and changes the title when
* discovery is finished
*/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
【问题讨论】:
标签: android bluetooth android-service android-bluetooth android-broadcastreceiver