Android 蓝牙类在启用、发现、列出配对设备以及连接到蓝牙设备方面相当易于使用。
我的计划是启动与另一个通过蓝牙提供网络共享的蓝牙设备的连接。
经过一番调查后,这看起来并不可行 - 看起来我必须自己实现配置文件,并拥有 root 访问权限来进行网络连接,并在应用程序中执行所有操作。
似乎也没有我可以通过“设置”触发的 Intent 来启动蓝牙连接,我能做的最好的就是将其打开。
我是否遗漏了一些东西 - 如果系统没有公开启动系统级蓝牙连接的方法,我会运气不好吗?
最佳答案
API 中已存在私有(private)配置文件:BluetoothPan
蓝牙 PAN(个人局域网)是识别蓝牙网络共享的正确名称。
此私有(private)类允许您通过公共(public) bool 连接(蓝牙设备设备)
和公共(public) bool 断开(蓝牙设备设备)连接到公开 PAN 蓝牙配置文件的设备以及与之断开连接
方法。
以下是连接到特定设备的示例 fragment :
String sClassName = "android.bluetooth.BluetoothPan";
class BTPanServiceListener implements BluetoothProfile.ServiceListener {
private final Context context;
public BTPanServiceListener(final Context context) {
this.context = context;
}
@Override
public void onServiceConnected(final int profile,
final BluetoothProfile proxy) {
Log.e("MyApp", "BTPan proxy connected");
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("AA:BB:CC:DD:EE:FF"); //e.g. this line gets the hardware address for the bluetooth device with MAC AA:BB:CC:DD:EE:FF. You can use any BluetoothDevice
try {
Method connectMethod = proxy.getClass().getDeclaredMethod("connect", BluetoothDevice.class);
if(!((Boolean) connectMethod.invoke(proxy, device))){
Log.e("MyApp", "Unable to start connection");
}
} catch (Exception e) {
Log.e("MyApp", "Unable to reflect android.bluetooth.BluetoothPan", e);
}
}
@Override
public void onServiceDisconnected(final int profile) {
}
}
try {
Class<?> classBluetoothPan = Class.forName(sClassName);
Constructor<?> ctor = classBluetoothPan.getDeclaredConstructor(Context.class, BluetoothProfile.ServiceListener.class);
ctor.setAccessible(true);
Object instance = ctor.newInstance(getApplicationContext(), new BTPanServiceListener(getApplicationContext()));
} catch (Exception e) {
Log.e("MyApp", "Unable to reflect android.bluetooth.BluetoothPan", e);
}
关于android - 以编程方式启动蓝牙系绳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9936551/