目前的Android蓝牙接口里,通过BluetoothDevice,我们只能调用到RFCOMM和SCO。
更底层的L2CAP接口并没有显式的提供出来。
其实通过java的反射机制,我们也是是可以调用到L2CAP接口的。
- import java.io.IOException;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
- import android.bluetooth.BluetoothSocket;
- public class BluetoothSocketFactory
- {
- public static final int TYPE_RFCOMM = 1;
- public static final int TYPE_SCO = 2;
- public static final int TYPE_L2CAP = 3;
- // address must use upper case
- public static final BluetoothSocket createBluetoothSocket(int type, int fd,
- boolean auth, boolean encrypt, String address, int port)
- throws IOException
- {
- BluetoothSocket socket = null;
- try
- {
- Constructor<BluetoothSocket> cs = BluetoothSocket.class
- .getDeclaredConstructor(int.class, int.class,
- boolean.class, boolean.class, String.class,
- int.class);
- if (!cs.isAccessible())
- {
- cs.setAccessible(true);
- }
- socket = cs.newInstance(type, fd, auth, encrypt, address, port);
- }
- catch (SecurityException e)
- {
- }
- catch (NoSuchMethodException e)
- {
- }
- catch (IllegalArgumentException e)
- {
- }
- catch (InstantiationException e)
- {
- }
- catch (IllegalAccessException e)
- {
- }
- catch (InvocationTargetException e)
- {
- }
- return socket;
- }
- public static void main(String args[])
- {
- BluetoothSocket socket = null;
- try
- {
- socket = BluetoothSocketFactory.createBluetoothSocket(
- BluetoothSocketFactory.TYPE_L2CAP, -1, false, false,
- "00:0B:24:35:4E:86", 22135);
- socket.connect();
- }
- catch (IOException e)
- {
- }
- finally
- {
- if (null != socket)
- {
- try
- {
- socket.close();
- }
- catch (IOException e)
- {
- }
- }
- }
- }
- }