Java / Android Bluetooth help

+2 Paul D · November 15, 2015
Hello, I am trying to communicate with my pc and android tablet with blue-tooth.  I am using eclispe as my ide to write my java files.  I have added the bluecove jar file as a referenced library. I am using the code from this this webpage   www.bluecove.org/bluecove/apidocs/overview-summary.html

When I run the ObexPutClient class I receive and can open the Hello.txt file on my android. What I would like to do is connect my android tablet and connect with blueterm2 and receive a string instead of a txt file.

When I run the PutServer class on my pc and I open BlueTerm on my android tablet and connect to my pc.  I can see the connection open but not any text i type in blueterm.

Any help would be greatly appreciated.  By directional bluetooth communication between a raspberry-pi using java and an android smartphone running an app is my ultimate end goal.   :)

import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.obex.*;

public class ObexPutClient {

    public static void main(String[] args) throws IOException, InterruptedException {

        String serverURL = null; // = "btgoep://0019639C4007:6";
        if ((args != null) && (args.length > 0)) {
            serverURL = args[0];
        }
        if (serverURL == null) {
            String[] searchArgs = null;
            // Connect to OBEXPutServer from examples
            // searchArgs = new String[] { "11111111111111111111111111111123" };
            ServicesSearch.main(searchArgs);
            if (ServicesSearch.serviceFound.size() == 0) {
                System.out.println("OBEX service not found");
                return;
            }
            // Select the first service found
            serverURL = (String)ServicesSearch.serviceFound.elementAt(0);
        }

        System.out.println("Connecting to " + serverURL);

        ClientSession clientSession = (ClientSession) Connector.open(serverURL);
        HeaderSet hsConnectReply = clientSession.connect(null);
        if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
            System.out.println("Failed to connect");
            return;
        }

        HeaderSet hsOperation = clientSession.createHeaderSet();
        hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
        hsOperation.setHeader(HeaderSet.TYPE, "text");

        //Create PUT Operation
        Operation putOperation = clientSession.put(hsOperation);

        // Send some text to server
        byte data[] = "Hello world!".getBytes("iso-8859-1");
        OutputStream os = putOperation.openOutputStream();
        os.write(data);
        os.close();

        putOperation.close();

        clientSession.disconnect(null);

        clientSession.close();
    }
}



OBEX Put Server
This class will start an OBEX service that will accept Put commands and print it to standard out.
import java.io.IOException;
import java.io.InputStream;

import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.obex.*;

public class OBEXPutServer {

static final String serverUUID = "11111111111111111111111111111123";

public static void main(String[] args) throws IOException {

LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);

SessionNotifier serverConnection = (SessionNotifier) Connector.open("btgoep://localhost:"
+ serverUUID + ";name=ObexExample");

int count = 0;
while(count < 2) {
RequestHandler handler = new RequestHandler();
serverConnection.acceptAndOpen(handler);
System.out.println("Received OBEX connection " + (++count));
}
}

private static class RequestHandler extends ServerRequestHandler {

public int onPut(Operation op) {
try {
HeaderSet hs = op.getReceivedHeaders();
String name = (String) hs.getHeader(HeaderSet.NAME);
if (name != null) {
System.out.println("put name:" + name);
}

InputStream is = op.openInputStream();

StringBuffer buf = new StringBuffer();
int data;
while ((data = is.read()) != -1) {
buf.append((char) data);
}

System.out.println("got:" + buf.toString());

op.close();
return ResponseCodes.OBEX_HTTP_OK;
} catch (IOException e) {
e.printStackTrace();
return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
}
}
}
}




Post a Reply

Replies

Oldest  Newest  Rating
+1 Paul D · November 19, 2015
With the code below that I found on the net I am able to send and receive a string from android to pc!  Nice!   I am testing with a windows pc but eventually I am going to compile a Jar with the ARM binaries so that  bluecove will run on the Raspberry Pi.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.bluetooth.DataElement;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class MyDiscoveryListener implements DiscoveryListener{
    
    private static Object lock=new Object();
    public ArrayList devices;
    
    public MyDiscoveryListener() {
        devices = new ArrayList();
    }
    
    public static void main(String[] args) {
        
        MyDiscoveryListener listener =  new MyDiscoveryListener();
        
        try{
            LocalDevice localDevice = LocalDevice.getLocalDevice();
            DiscoveryAgent agent = localDevice.getDiscoveryAgent();
            agent.startInquiry(DiscoveryAgent.GIAC, listener);
            
            try {
                synchronized(lock){
                    lock.wait();
                }
            }
            catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
            
            System.out.println("Device Inquiry Completed. ");
                  
            UUID[] uuidSet = new UUID[1];
            uuidSet[0]=new UUID(0x1105); //OBEX Object Push service
            
            int[] attrIDs =  new int[] {
                    0x0100 // Service name
            };
            
            for (RemoteDevice device : listener.devices) {
                agent.searchServices(
                        attrIDs,uuidSet,device,listener);
                
                try {
                    synchronized(lock){
                        lock.wait();
                    }
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                }
                
                System.out.println("Service search finished.");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass arg1) {
        String name;
        try {
            name = btDevice.getFriendlyName(false);
        } catch (Exception e) {
            name = btDevice.getBluetoothAddress();
        }
        
        devices.add(btDevice);
        System.out.println("device found: " + name);
    }

    @Override
    public void inquiryCompleted(int arg0) {
        synchronized(lock){
            lock.notify();
        }
    }

    @Override
    public void serviceSearchCompleted(int arg0, int arg1) {
        synchronized (lock) {
            lock.notify();
        }
    }

    @Override
    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        for (int i = 0; i < servRecord.length; i++) {
            String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
            if (url == null) {
                continue;
            }
            DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
            if (serviceName != null) {
                System.out.println("service " + serviceName.getValue() + " found " + url);
                        
                try {
                    startServer();
                } catch (IOException e) {
                
                    e.printStackTrace();
                }
                
                System.out.println("service found " + url);
            }
        }
    }
    
    private static void startServer() throws IOException{

        //Create a UUID for SPP
        UUID uuid = new UUID("1101", true);
        //Create the servicve url
        String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";

        //open server url
        StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );

        //Wait for client connection
        System.out.println("\nServer Started. Waiting for clients to connect...");
        StreamConnection connection=streamConnNotifier.acceptAndOpen();

        RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
        System.out.println("Remote device address: "+dev.getBluetoothAddress());
        System.out.println("Remote device name: "+dev.getFriendlyName(true));

        //read string from spp client
        InputStream inStream=connection.openInputStream();
        BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
        String lineRead=bReader.readLine();
        System.out.println(lineRead);

        //send response to spp client
        OutputStream outStream=connection.openOutputStream();
        PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
        pWriter.write("Response String from SPP Server\r\n");
        pWriter.flush();
        pWriter.close();
        streamConnNotifier.close();
    }
}
+1 Paul D · November 20, 2015
Here is the solution I was looking for, I was able to figure it out on my own. 


public static void main(String[] args) {
                
        try {
            startServer();
        } catch (IOException e) {
            e.printStackTrace();
        }
          }
    
    private static void startServer() throws IOException{

        UUID uuid = new UUID("1101", true);
        String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
        StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
        System.out.println("\nServer Started. Waiting for client to connect...");
        
        StreamConnection connection=streamConnNotifier.acceptAndOpen();
        
        InputStream inStream = connection.openInputStream();
        OutputStream outStream = connection.openOutputStream();
        PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(
                outStream));
        BufferedReader bReader = new BufferedReader(new InputStreamReader(
                inStream));
        
        int x = 0;
        
        while (x == 0) {
            String lineRead = bReader.readLine();
            System.out.println(lineRead);
            pWriter.write("Response String back to ANDROID PHONE " + lineRead
                    + "\r\n");
            pWriter.flush();
            if (lineRead.trim().toLowerCase().equals("quit"))
            {
                x++;
            }
        }
        pWriter.close();
        streamConnNotifier.close();
    }
}
  • 1

Java / Android Development

107,039 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator