create Bluetooth Rfcomm Socket - Android Bluetooth

Android examples for Bluetooth:Bluetooth Data Transfer

Description

create Bluetooth Rfcomm Socket

Demo Code


//package com.java2s;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

import android.util.Log;

public class Main {
    private static final String TAG = "BluetoothUtils";
    private static final boolean D = true;

    public static BluetoothSocket createRfcommSocket(BluetoothDevice device) {
        BluetoothSocket tmp = null;//  ww w .  j ava2  s  .c  om

        try {
            Class class1 = device.getClass();
            Class aclass[] = new Class[1];
            aclass[0] = Integer.TYPE;
            Method method = class1.getMethod("createRfcommSocket", aclass);
            Object aobj[] = new Object[1];
            aobj[0] = Integer.valueOf(1);

            tmp = (BluetoothSocket) method.invoke(device, aobj);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            if (D)
                Log.e(TAG, "createRfcommSocket() failed", e);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            if (D)
                Log.e(TAG, "createRfcommSocket() failed", e);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            if (D)
                Log.e(TAG, "createRfcommSocket() failed", e);
        }

        return tmp;
    }
}

Related Tutorials