Android 蓝牙类在启用、发现、列出配对设备和连接到蓝牙设备方面相当容易使用。
我的计划是启动与另一个通过蓝牙提供网络共享的蓝牙设备的连接。
经过一番调查,这看起来不可行 - 看起来我必须自己实现配置文件,并拥有 root 访问权限才能进行网络连接,并在应用程序中完成所有操作。
我似乎也没有可以通过设置触发来启动蓝牙连接的意图,我能做的最好的就是打开它。
我是否遗漏了什么——如果系统没有公开启动系统级蓝牙连接的方法,我是不是运气不好?
API 中已存在私有配置文件:BluetoothPan
蓝牙 PAN(个人局域网)是识别蓝牙网络共享的正确名称。
public boolean connect(BluetoothDevice device)
此私有类允许您通过和方法连接和断开暴露 PAN 蓝牙配置文件的设备public boolean disconnect(BluetoothDevice device)
。
以下是连接到特定设备的示例代码段:
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);
}