以编程方式启动蓝牙系绳

时间:2012-03-30 03:17:45

标签: android bluetooth tethering

Android蓝牙类在启用,发现,列出配对设备以及连接蓝牙设备方面相当容易使用。

我的计划是启动与另一个通过蓝牙提供网络共享的蓝牙设备的连接。

经过一些调查后,这看起来并不可行 - 看起来我必须自己实施配置文件,并拥有root权限进行网络连接,并在应用程序中执行所有操作。

似乎没有意图我可以通过设置触发启动蓝牙连接,我能做的最好就是打开它。

我错过了什么 - 如果系统没有公开启动系统级蓝牙连接的方法,我运气不好吗?

1 个答案:

答案 0 :(得分:3)

API中已存在私人资料:BluetoothPan

蓝牙PAN(个人区域网络)是识别蓝牙网络共享的正确名称。

此私有类允许您通过public boolean connect(BluetoothDevice device)public boolean disconnect(BluetoothDevice device)方法连接和断开暴露PAN蓝牙配置文件的设备。

以下是连接到特定设备的示例代码段:

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);
}