Connecting to PC From Mobile Using Bluetooth in Java

35
Connecting to PC from mobile using bluetooth in java-Question Question subject: Connecting to PC from mobile using bluetooth in java Posted: Fri Jul 25, 2008 6:43 pm I will talk about how to make data transfer from your mobile to your PC .The mobile side will be a j2me application.The server side is J2se application .To make such communication using bluetooth you need to open a virtual COM in your pc and assign this virtual COM to your paired mobile .Paired devices means an same PIN Code entered in both sides (mobile and PC ) .In my case i worked on bluecove external adapter .There is an application for bluecove device that allow me to assign COMs to a specific mobile.In my system i was sending images from my phone to PC server using bluetooth. In server side : You will need some packages to make the work done .in my case i used two packages bluecove-2.0.2.jar and avetanaObex.jar . Here is code from it java code ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package sift; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import java.util.logging.Logger; import javax.bluetooth.DiscoveryAgent; import javax.bluetooth.LocalDevice; import javax.bluetooth.UUID; import javax.microedition.io.Connector; import javax.microedition.io.StreamConnection; import javax.microedition.io.StreamConnectionNotifier; import javax.swing.ImageIcon;

description

Connecting to PC From Mobile Using Bluetooth in Java

Transcript of Connecting to PC From Mobile Using Bluetooth in Java

Connecting to PC from mobile using bluetooth in java-Question

Question subject: Connecting to PC from mobile using bluetooth in javaPosted: Fri Jul 25, 2008 6:43 pm

I will talk about how to make data transfer from your mobile to your PC .The mobile side will be a j2me application.The server side is J2se application .To make such communication using bluetooth you need to open a virtual COM in your pc and assign this virtual COM to your paired mobile .Paired devices means an same PIN Code entered in both sides (mobile and PC ) .In my case i worked on bluecove external adapter .There is an application for bluecove device that allow me to assign COMs to a specific mobile.In my system i was sending images from my phone to PC server using bluetooth.

In server side : You will need some packages to make the work done .in my case i used two packages bluecove-2.0.2.jar and avetanaObex.jar . Here is code from it java code ?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260package sift;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.logging.Level;import java.util.logging.Logger;import javax.bluetooth.DiscoveryAgent;import javax.bluetooth.LocalDevice;import javax.bluetooth.UUID;import javax.microedition.io.Connector;import javax.microedition.io.StreamConnection;import javax.microedition.io.StreamConnectionNotifier;import javax.swing.ImageIcon;/*** A class that demonstrates Bluetooth communication between server mode PC and* client mode device through serial port profile.* * @see sourceforge.net/projects/bluecove : BlueCove - JSR-82* implementation*/public class PCServerCOMM {/*-* ================* Bluetooth Server* ================* * This example application is a straighforward implementation of * a bluetooth server.* * * Usage* =====* * Start the program. Events are logged by printing them out with standard * output stream. Once the server is up and ready to accept connections, * connect to server with client.* * * How it Works* ============* * The application starts a loop to wait for a new connection. After a new * connection is reseived the connection is handled. In the handling * operation few tokens and end token is written to connection stream. * Each read token is logged to standard output. After handling session * the loop continues by waiting for a new connection.* *//*-* * ---- Bluetooth attributes ----*/// serial port profileprotected String UUID = new UUID("1101", true).toString();protected int discoveryMode = DiscoveryAgent.GIAC; // no paring neededpublic static InputStream in;public static OutputStream out;private static boolean ServerRun = true;Image aa;MOBILEOR_GUI frame;/*-* * ---- Connection handling attributes ----*/protected int endToken = 255;public PCServerCOMM(MOBILEOR_GUI frame) {this.frame = frame;ServerRun = true;try {LocalDevice device = LocalDevice.getLocalDevice();device.setDiscoverable(DiscoveryAgent.GIAC);String url = "btspp://localhost:" + UUID + ";name=PCServerCOMM";log("Create server by uri: " + url);StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector.open(url);serverLoop(notifier);} catch (Throwable e) {log(e);}}private void serverLoop(final StreamConnectionNotifier notifier) {Thread handler = new Thread() {@Overridepublic void run() {try {while (ServerRun) { // infinite loop to accept connections.log("Waiting for connection...");handleConnection(notifier.acceptAndOpen());}} catch (Exception e) {log(e);}try {Thread.sleep(200);} catch (InterruptedException ex) {Logger.getLogger(PCServerCOMM.class.getName()).log(Level.SEVERE, null, ex);}}};handler.start();}private void handleConnection(StreamConnection conn) throws IOException {out = conn.openOutputStream();in = conn.openInputStream();startReadThread(in);log("Connection found...");/*try { // to write some tokens through the bluetooth linkint[] tokens = new int[] { 1, 3, 5, 7, endToken };for (int i = 0; i < tokens.length; i++) {out.write(tokens[i]);out.flush();log("write:" + tokens[i]);// wait a sec before next write.Thread.sleep(1 * 1000);}} catch (Exception e) {log(e);} finally {log("Close connection.");if (conn != null) {try {conn.close();} catch (IOException e) {}}}* */}private void startReadThread(final InputStream in) {Thread reader = new Thread() {@Overridepublic void run() {FileOutputStream f1 = null;// System.out.println("Image data");File directory = new File("C:/Image/");String path = "image/image.png";String image = "";try {f1 = new FileOutputStream(path,false);} catch (FileNotFoundException ex) {Logger.getLogger(PCServerCOMM.class.getName()).log(Level.SEVERE, null, ex);}byte[] s = new byte[512];boolean falg = true;log("Waiting for image data");try {while (true) {int r = in.read(s);if (r != -1) {falg = false;try {//s=Base64.decode(new String(s).intern());// image = image + new String(s,0,r);f1.write(s, 0, r);f1.flush();} catch (IOException e) {System.out.println("Problems creating the file");}}if (!falg && (r < s.length)) {// System.out.println("Frame !!!");f1.flush();f1.close(); aa = new ImageIcon(path).getImage();new FrameImage(aa, 1);SIFT sift = new SIFT(path, "scale2.jpg", "welcome");frame.setImg(aa);frame.repaint();BufferedImage buff = new BufferedImage(aa.getWidth(null), aa.getHeight(null), BufferedImage.TYPE_INT_RGB);// buff.createGraphics().drawImage(sift.oriented_Image(), 0, 0, null);// OrientationForm orientionResult = new OrientationForm(buff);// orientionResult.showOrientationResult();MOBILEOR_GUI.AppendTostatus(sift.getATree().getMatchingInfo());// setNearestImages(sift.getNearest_5_imgs());// frame.createNearestWindow(sift.getNearest_5_imgs(), orientionResult);// frame.getDisplayNearest().setSize(frame.getDesktopWidth(), 200);// frame.getDisplayNearest().setLocation(0, orientionResult.getHeight() + 5);// frame.getDesktop().add(frame.getDisplayNearest());break;}}} catch (Throwable e) {log(e);} finally {if (in != null) {try {log("Image transfering done...");in.close();} catch (IOException e) {}}}}};reader.start();}/*-* ------- Utility section -------*/private void log(String msg) {MOBILEOR_GUI.AppendTostatus(msg + "\n");}private void log(Throwable e) {log(e.getMessage());e.printStackTrace();}public Image getImage() {return aa;}public static void StopServer() {ServerRun = false;}/*-* ------- Bootstrap section, i.e., main method -------*/}

About the mobile side you can make a midlet and install it on your mobile .Here is some codes :

java code ?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Vector;import javax.bluetooth.BluetoothStateException;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.lcdui.Command;import javax.microedition.lcdui.CommandListener;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Displayable;import javax.microedition.lcdui.Form;import javax.microedition.lcdui.List;import javax.microedition.midlet.MIDlet;import javax.microedition.midlet.MIDletStateChangeException;/*** A class that demonstrates Bluetooth communication between client mode device* and server mode PC through serial port profile.*/public class DeviceClientCOMM implements DiscoveryListener, CommandListener {/*-* ================* Bluetooth Client* ================* * This example application is a straightforward implementation of * making a connection throught bluetooth link and using it. * * * Usage* =====* * Once the system is started the information area is filled with logging* information. Wait until combo box is enabled (if there's any bluetooth * device around) and select a device from the combo box. A connection * is constructed to selected device after selection. * * After connection is constructed succesfully the application * operates as an echo client, i.e., everything that is read is written * back to the server. All information is also written into the information * area.* * * How it Works* ============* * The example consist of three different operations. Operations need to * be executed in the dependency order. * * 1) *Inquiry method* is used to search all available devices. The combo * box's data model is filled with found bluetooth devices.* * 2) *Service search* is used to search serial port profile service from the* selected device. The search is started after the user selects the* device from the combo box.* * 3) *Stream handling* communicates with the server through the bluetooth * link. This example operates in echo loop until stop token is found.* * * Special Debug Mode* ==================* * There's a special debug mode which speeds up development by skipping the* inquiry method to resolve the remote device. In the debug mode the device's * bluetooth address is provided by the developer.*//*-* * ---- Debug attributes ----*/static final boolean DEBUG = false;static final String DEBUG_address = "0013FDC157C8"; // N6630/*-* * ---- Bluetooth attributes ----*/protected UUID uuid = new UUID(0x1101); // serial port profileprotected int inquiryMode = DiscoveryAgent.GIAC; // no pairing is neededprotected int connectionOptions = ServiceRecord.NOAUTHENTICATE_NOENCRYPT;/*-* * ---- Echo loop attributes ----*/protected int stopToken = 255;/*-* * ---- GUI attributes ----*/private Command backCommand = new Command("Back", Command.BACK, 1);protected Form infoArea = new Form("Bluetooth Client");protected Vector deviceList = new Vector();private CameraMIDlet mymidlet;private byte[] imag;public DeviceClientCOMM(CameraMIDlet m, byte[] imag) {mymidlet = m;this.imag = imag;infoArea.setCommandListener(this);infoArea.addCommand(backCommand);try {startApp();} catch (MIDletStateChangeException ex) {ex.printStackTrace();}}protected void startApp() throws MIDletStateChangeException {makeInformationAreaGUI();if (DEBUG) // skip inquiry in debug mode{startServiceSearch(new RemoteDevice(DEBUG_address) {});} else {try {startDeviceInquiry();} catch (Throwable t) {log(t);}}}/*-* ------- Device inquiry section -------*/private void startDeviceInquiry() {try {log("Start inquiry method - this will take few seconds...");DiscoveryAgent agent = getAgent();agent.startInquiry(inquiryMode, this);} catch (Exception e) {log(e);}}public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {log("A device discovered (" + getDeviceStr(btDevice) + ")");deviceList.addElement(btDevice);}public void inquiryCompleted(int discType) {log("Inquiry compeleted. Please select device from combo box.");makeDeviceSelectionGUI();}/*-* ------- Service search section -------*/private void startServiceSearch(RemoteDevice device) {try {log("Start search for Serial Port Profile service from " + getDeviceStr(device));UUID uuids[] = new UUID[]{uuid};getAgent().searchServices(null, uuids, device, this);} catch (Exception e) {log(e);}}/*** This method is called when a service(s) are discovered.This method starts* a thread that handles the data exchange with the server.*/public void servicesDiscovered(int transId, ServiceRecord[] records) {log("Service discovered.");for (int i = 0; i < records.length; i++) {ServiceRecord rec = records[i];String url = rec.getConnectionURL(connectionOptions, false);handleConnection(url);}}public void serviceSearchCompleted(int transID, int respCode) {String msg = null;switch (respCode) {case SERVICE_SEARCH_COMPLETED:msg = "the service search completed normally";break;case SERVICE_SEARCH_TERMINATED:msg = "the service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch()";break;case SERVICE_SEARCH_ERROR:msg = "an error occurred while processing the request";break;case SERVICE_SEARCH_NO_RECORDS:msg = "no records were found during the service search";break;case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:msg = "the device specified in the search request could not be reached or the local device could not establish a connection to the remote device";break;}log("Service search completed - " + msg);}/*-* ------- The actual connection handling. -------*/private void handleConnection(final String url) {Thread echo = new Thread() {public void run() {StreamConnection stream = null;InputStream in = null;OutputStream out = null;try {log("Connecting to server by url: " + url);stream = (StreamConnection) Connector.open(url);log("Bluetooth stream open.");// InputStream in = stream.openInputStream();out = stream.openOutputStream();in = stream.openInputStream();startReadThread(in);// String stringImage = Base64.encode(imag);log("Start echo loop.");out.write(imag);out.flush();// out.flush();// stream.close();} catch (IOException e) {log(e);} finally {log("Bluetooth stream closed.");if (out != null) {try {out.close();stream.close();logSet("Image Transfer done\n----------------\n\nWaiting for results...");} catch (IOException e) {log(e);}}}}};echo.start();}private void startReadThread(final InputStream in) {Thread reader = new Thread() {public void run() {byte[] s = new byte[512];//boolean flag = true;try {while (true) {int r = in.read(s);if (r != -1) {logSet(new String(s, 0, r));} else {break;}Thread.sleep(200);}} catch (Throwable e) {log(e);} finally {if (in != null) {try {in.close();} catch (IOException e) {}}}}};reader.start();}/*-* ------- Graphic User Interface section -------*/private void makeInformationAreaGUI() {infoArea.deleteAll();Display.getDisplay(mymidlet).setCurrent(infoArea);}private void makeDeviceSelectionGUI() {final List devices = new List("Select a device", List.IMPLICIT);for (int i = 0; i < deviceList.size(); i++) {devices.append(getDeviceStr((RemoteDevice) deviceList.elementAt(i)), null);}devices.setCommandListener(newCommandListener( ) {public void commandAction(Command arg0, Displayable arg1) {makeInformationAreaGUI();startServiceSearch((RemoteDevice) deviceList.elementAt(devices.getSelectedIndex()));}});Display.getDisplay(mymidlet).setCurrent(devices);}synchronized private void log(String msg) {infoArea.append(msg);infoArea.append("\n\n");}synchronized private void logSet(String msg) {infoArea.deleteAll();infoArea.append(msg);infoArea.append("\n\n");}private void log(Throwable e) {log(e.getMessage());}/*-* ------- Utils section - contains utility functions -------*/private DiscoveryAgent getAgent() {try {return LocalDevice.getLocalDevice().getDiscoveryAgent();} catch (BluetoothStateException e) {throw new Error(e.getMessage());}}private String getDeviceStr(RemoteDevice btDevice) {return getFriendlyName(btDevice) + " - 0x" + btDevice.getBluetoothAddress();}private String getFriendlyName(RemoteDevice btDevice) {try {return btDevice.getFriendlyName(false);} catch (IOException e) {return "no name available";}}public void commandAction(Command arg0, Displayable arg1) {mymidlet.DisplayMainList();}}

The mobile will start searching for the neighbor bluetooth turned on devices after that you will choose your PC .

_________________Please recommend my post if you found it helpful.

Author: msi_333

Posts: 2722Havethanks: 70 time

For this message the author msi_333 has received gratitude : Bhupendra

Question subject: Re: Connecting to PC from mobile using bluetooth in javaPosted: Tue Jan 27, 2009 10:14 pm

Hi msi_333, your Post is great! Very useful

But I cannot understand some things ...

I.E. :

What is the meaning of MOBILEOR_GUI ?Quote:MOBILEOR_GUI frame;

And what about this?Quote:new FrameImage(aa, 1);SIFT sift = new SIFT(path, "scale2.jpg", "welcome");

I don't know where are these Classes (MOBILEOR_GUI, FrameImage, SIFT)

Sorry for my poor English

If you can send me the complete code of the Server I'll be grateful ([email protected])

Thanks in advance

Author: eliasturbay

Posts: 1Havethanks: 0 time

Question subject: Re: Connecting to PC from mobile using bluetooth in javaPosted: Tue Jan 27, 2009 10:26 pm

Hi ,thank you for your reply these lines of codes not related to the connection of bluetooth , it is related to my project function , for example , SIFT is an object recognition algorithm .

_________________Please recommend my post if you found it helpful.

Author: msi_333

Posts: 2722Havethanks: 70 time

Question subject: Re: Connecting to PC from mobile using bluetooth in javaPosted: Sat Apr 18, 2009 8:59 pm

please help meeeeeeeeeim an a graduate student and part of my final project is to transfer a text file from a pc to mobile

if we went to transfer text file the uuid not mention and i not found it although i search a lot on it please help me if you can and the reminder time is very little

Author: juddy

Posts: 4Havethanks: 0 time

Question subject: Re: Connecting to PC from mobile using bluetooth in javaPosted: Mon Apr 20, 2009 6:59 pm

hi thankx it is really working good in iphone.do you have any code for n96 nokia.________________________Medical wound DressingsHeel Pain

Last edited by jack2008 on Thu May 14, 2009 2:39 pm, edited 1 time in total.

Author: jack2008

Posts: 3Havethanks: 0 time

Question subject: Re: Connecting to PC from mobile using bluetooth in javaPosted: Mon Apr 27, 2009 8:34 am

hi msi_333 ,

Nice post !I am facing an small problem with a similar code for just text transfer , I have a bluesoliel stack and bluecove library .when i run the application the device gets discovered fromthe client and stack gets initialized and the window pops up asking for permission to open up virtual com ports but the application still ends in a loop waiting for connection , when i use hyperterminal instead of the app i get read n write back in the client .

init:deps-jar:compile:BlueCove version 2.0.2 on bluesoleilCreate server by uri: btspp://localhost:000011010000100080000 ... ServerCOMMWaiting for connection...

wat could be the problem please help me out!

sriram

Author: sriram86

Posts: 1Havethanks: 0 time

Question subject: Re: Connecting to PC from mobile using bluetooth in javaPosted: Mon Apr 27, 2009 5:28 pm

this gonna be helpful to me, thanks for sharing the code for java

Airtel :To Transfer Balance In Airtel Just Dial *141# And Follow The Onscreen Instructions.You Can Transfer From 5 To 30 Rupees Of Balance In Airtel.Tata Docomo :To Transfer Balance In Tata Docomo SMS asBT MobileNumber Amount And Send It To 54321.E.g. BT 9876543210 30 To Transfer 30 Rupees Of Balance.

!dea :To Transfer Balance In !dea Network Send SMS asGIVE MobileNumber Amount And Send It To 55567.E.g.GIVE 9876543210 30 To Transfer 30 Rupees.Vodafone :To Transfer Balance In Vodafone Dial*131*Amount*Mobile No#E.g.*131*50*9876543210# To Transfer 50 Rupees Of Balance.Uninor :To Transfer Balance In Uninor Just Dial*202*MobileNumber*Amount#E.g.*202*9876543210*30# To Transfer 30 Rupees.Aircel :To Transfer Balance In Aircel Just Dial*122*666# And Follow The Instructions.You Can Transfer 10,20 Or 100 Rupees Of Balance.BSNL :To Transfer Balance In BSNL Just Send SMS GIFT MobileNumber Amount To 53733.E.g. GIFT9876543210 50 To Transfer 50 Rupees Of Balance.