connect and Write data to Bluetooth device - Android Bluetooth

Android examples for Bluetooth:Bluetooth Data Transfer

Description

connect and Write data to Bluetooth device

Demo Code


//package com.java2s;
import java.io.OutputStream;
import java.lang.reflect.Method;

import java.util.UUID;
import android.annotation.TargetApi;

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

import android.os.Build;
import android.util.Log;

public class Main {
    static final UUID UUID_RFCOMM_GENERIC = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");

    @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
    public static boolean connectWrite(BluetoothDevice device, byte[] text,
            int delay) {
        BluetoothAdapter mBTAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice mBTDevice = mBTAdapter.getRemoteDevice(device
                .getAddress());//w w  w .j  a  v a 2 s . co  m
        BluetoothSocket mBTSocket;
        try {
            mBTSocket = mBTDevice
                    .createInsecureRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
            mBTSocket.connect();
            OutputStream mBTOutputStream = mBTSocket.getOutputStream();
            mBTOutputStream.write(text);
            mBTOutputStream.flush();
            Thread.sleep(delay);
            mBTOutputStream.close();
            return true;
        } catch (Exception e1) {
            e1.printStackTrace();
            return false;
        }
    }

    @SuppressWarnings({ "unchecked", "rawtypes", "unused" })
    public static Boolean connect(BluetoothDevice bdDevice) {
        Boolean bool = false;
        try {
            Log.i("Log", "service metohd is called ");
            Class cl = Class.forName("android.bluetooth.BluetoothDevice");
            Class[] par = {};
            Method method = cl.getMethod("createBond", par);
            Object[] args = {};
            bool = (Boolean) method.invoke(bdDevice);
        } catch (Exception e) {
            Log.i("Log", "Inside catch of serviceFromDevice Method");
            e.printStackTrace();
        }
        return bool.booleanValue();
    }
}

Related Tutorials