Sending files to mobile phone using Bluetooth and OBEX

My previous posting “Using Bluetooth stack in desktop application” was quite a success if measured by the number of comments. It seems that there aren’t many tutorials or articles about the Desktop usage of Bluetooth.

Here is a next chapter in the same category: using Bluetooth to send files from a computer to a mobile phone.

Bluetooth file sender application

Read on if you are interested…

I wrote this small application so that I could send files (images) to my phone using the Bluetooth.

Creating a new application

I used NetBeans IDE to create this application. First I created a new Java application project. I created a following files for the app:

  • ApplicationContext.java - Contains list of devices near-by
  • ApplicationFrame.java – Actual UI, extends JFrame
  • BluetoothBrowser.java - Helper class to browse near-by devices
  • ListItem.java - DAO class used by ApplicationFrame
  • Main.java - Application entry point
  • SendFileTask.java – The OBEX magic for sending a file

I designed the UI with NetBeans IDE’s Matisse editor, which allows developer to design desktop user interfaces very easily.

Designing OBEX file sender UI

Next I added code for searching devices when user presses the Refresh button. This was already discussed in the previous article. Also simple coding was done for browsing the file when Browse button gets clicked.

Next step was to add the actual business logic for sending the file to a selected Bluetooth device when Upload file to device button is clicked.

Code for upload button action performed

  1. // Get selected item from list
  2. ListItem selectedItem =
  3.     (ListItem) deviceList.getSelectedValue();
  4. RemoteDevice device = selectedItem.getDevice();
  5.  
  6. // Build URL for the bluetooth device, note the port 9
  7. String url =
  8.     "btgoep://" + device.getBluetoothAddress() + ":9";
  9.  
  10. // Get file as bytes
  11.     new FileInputStream(fileTextField.getText());
  12. File f = new File(fileTextField.getText());
  13. int size = (int) f.length();
  14. byte[] file = new byte[size];
  15. stream.read(file);
  16.  
  17. // Filename
  18. String filename = f.getName();
  19.  
  20. // Trigger the task in a different thread
  21. // so it won’t block the UI
  22. SendFileTask task =
  23.     new SendFileTask(url, file, filename);
  24. Thread thread = new Thread(task);
  25. task.run();

Next step was to write the code for sending a file using the OBEX protocol.

Code for send file task

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package bluetoothfileexchange;
  6.  
  7. import java.io.OutputStream;
  8. import javax.microedition.io.Connection;
  9. import javax.microedition.io.Connector;
  10. import javax.obex.ClientSession;
  11. import javax.obex.HeaderSet;
  12. import javax.obex.Operation;
  13.  
  14. /**
  15.  *
  16.  * @author Tommi Laukkanen (tlaukkanen at gmail dot com)
  17.  */
  18. public class SendFileTask implements Runnable {
  19.  
  20.     private String btConnectionURL;
  21.     private byte[] file;
  22.     private String filename;
  23.  
  24.     public SendFileTask(
  25.             String url, byte[] file, String filename) {
  26.         this.btConnectionURL = url;
  27.         this.file = file;
  28.         this.filename = filename;
  29.     }
  30.  
  31.     public void run() {
  32.  
  33.         try {
  34.             Connection connection =
  35.                 Connector.open( btConnectionURL );
  36.             // connection obtained
  37.  
  38.             // now, let’s create a session
  39.             // and a headerset objects
  40.             ClientSession cs =
  41.                 (ClientSession) connection;
  42.             HeaderSet hs = cs.createHeaderSet();
  43.  
  44.             // now let’s send the connect header
  45.             cs.connect(hs);
  46.  
  47.             hs.setHeader(HeaderSet.NAME, filename);
  48.             // content-type could be
  49.             // checked from a filename
  50.             hs.setHeader(HeaderSet.TYPE, "image/jpeg");
  51.             hs.setHeader(
  52.                 HeaderSet.LENGTH,
  53.                 new Long(file.length));
  54.  
  55.             Operation putOperation = cs.put(hs);
  56.  
  57.             OutputStream outputStream =
  58.                 putOperation.openOutputStream();
  59.             outputStream.write(file);
  60.             // file push complete
  61.  
  62.             outputStream.close();
  63.             putOperation.close();
  64.  
  65.             cs.disconnect(null);
  66.  
  67.             connection.close();
  68.         } catch (Exception e) {
  69.             e.printStackTrace();
  70.         }
  71.     }
  72. }

That was it. Now when the application is run, user can send a selected file to a selected Bluetooth device. I get a normal “Message received” notification on my mobile phone, Nokia N80, when I send a new image file to the phone.

You can download the whole project along with source codes from here.

  • somendu maiti

    i am unable to find the device. i have tried the code both using bletooth dongle and as well as internal bluetooth adapter for laptop.. please help me out

  • http://utsavgandhi.blogspot.com Utsav

    Hello Tommi,

    Its nice of you to post your code…

    However, I’d request you if you could throw some light on “Synchronization” and also on the case if I’d like to send a file from the mobile phone to my computer….

    I am required to send-receive data to and from a phone that is connected to the computer using a USB cord…

    I am aware of the fact that Nokia PC Suite allows it but have been told to abstain from its usage.

    Awaiting ur reply…

    Thanks..

  • Bruno

    Hello Tommi

    I adapt your code and it’s works fine, but I still have a problem.
    when I send a file, Windows needs pairing mobile and computer.
    the application I developped must works without pairing.
    I want to send a file from computer to mobile with a default pin code like “0000″.
    do you think it’s possible ? and how ?
    a param in obex ?
    a bluetoothstack ? (witch one ?)

    thanks for your help
    bruno

  • cereous

    hi, nice work!

    is this also going to work for pc to pc file transfer, or there’s need to change the port number? pls help

  • ahmed said

    hi Tommi really thanks a lot for this helpful codes but i want to send sms text message only or just string can you give me an example, again thanks a lot

  • prabhu

    Hi all

    good work .But i can send file to only some mobiles for others it gives exception like
    Failed to connect; [10064] A socket operation failed because the destination host was down.
    javax.bluetooth.BluetoothConnectionException: Failed to connect; [10064] A socket operation failed because the destination host was down.
    at com.intel.bluetooth.BluetoothStackMicrosoft.connect(Native Method)
    at com.intel.bluetooth.BluetoothStackMicrosoft.access$700(BluetoothStackMicrosoft.java:44)
    at com.intel.bluetooth.BluetoothStackMicrosoft$ConnectThread.run(BluetoothStackMicrosoft.java:651)

    i want to send for every mobile.Can anybody help me for this.One more think for specified day particular file has to be sent only once.Also it should give response message as successful or failed

    • Sorin Oprita

      I have the same problem and I was wondering if you have found the solution. I am trying to send files to android phones and the 2 different phones I tried both gave me this exception. I think it has something to do with that pin required when pairing devices.

      Also, this is pretty urgent and I would appreciate a quick answer.

      Thanks in advance.

  • daniele

    Hello, congratulations for the program, you can have the code? I need for a university examination …. email: danieleperrotta@hotmail.it thanks very much!!:D

  • danger

    When I pressed the refresh button, this error appeared.
    My bluetooth is enabled. Please help me. Thanks

    Nov 13, 2010 7:12:16 PM ApplicationFrame refreshButtonActionPerformed
    SEVERE: null
    javax.bluetooth.BluetoothStateException: Bluetooth Device is not ready
    at com.intel.bluetooth.BluetoothStackWIDCOMM.runDeviceInquiryImpl(Native Method)
    at com.intel.bluetooth.BluetoothStackWIDCOMM.access$000(BluetoothStackWIDCOMM.java:43)
    at com.intel.bluetooth.BluetoothStackWIDCOMM$1.runDeviceInquiry(BluetoothStackWIDCOMM.java:367)
    at com.intel.bluetooth.DeviceInquiryThread.run(DeviceInquiryThread.java:103)

  • Slim

    How do you propose I change the code in the run method to keep the connection open for a longer period? Like a server-client scenario where alot of small messages is sent between server and client. Seems to costly to create a new put-operation and open/close the streams for each message sent.

  • Jjdanger

    Hi! I have a problem with your code. Its not working when I’m trying to transfer file from PC to PC.. Can anyone help me to fix this problem..Thanks!

  • Manasa

    hi tommi…

    a very good code and when i run it,search is working fine…but after the device s getting discovered the upload is not workin…when i press upload i get the following errors…

    Exception: Failed to connect; [10064] A socket operation failed because the destination host was down.
    javax.bluetooth.BluetoothConnectionException: Failed to connect; [10064] A socket operation failed because the destination host was down.
    at com.intel.bluetooth.BluetoothStackMicrosoft.connect(Native Method)
    at com.intel.bluetooth.BluetoothStackMicrosoft.access$700(BluetoothStackMicrosoft.java:44)
    at com.intel.bluetooth.BluetoothStackMicrosoft$ConnectThread.run(BluetoothStackMicrosoft.java:651)

    please help me out….this is for my final year project…..as soon as possible…

  • Shaashabona

    THNQQQQQQ YO HAVE SAVED MY LIFE!!:D:D 

    I am having my Graduation project and suffered a lot with and bluetooth!!THNX A LOT ^^

  • Edmonflancia20

    can you convert it to vb.net?
     

  • Rajesh .V

    When i am running the application it’s not showing any devices which is turned on..It’s showing the following error..
    LOG: Start discoveryNative Library intelbth not avalableNative Library bluecove not avalableException in thread “AWT-EventQueue-0″ java.lang.Error: BlueCove not avalable at com.intel.bluetooth.BlueCoveImpl.createDetectorOnWindows(BlueCoveImpl.java:214) at com.intel.bluetooth.BlueCoveImpl.(BlueCoveImpl.java:109) at com.intel.bluetooth.BlueCoveImpl.(BlueCoveImpl.java:35) at com.intel.bluetooth.BlueCoveImpl$SingletonHolder.(BlueCoveImpl.java:82) at com.intel.bluetooth.BlueCoveImpl.instance(BlueCoveImpl.java:195) at javax.bluetooth.LocalDevice.(LocalDevice.java:65) at javax.bluetooth.LocalDevice.getLocalDevice(LocalDevice.java:80) at com.substanceofcode.bluetooth.BluetoothBrowser.(BluetoothBrowser.java:34) at com.substanceofcode.presence.Controller$1.run(Controller.java:45) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705) at java.awt.EventQueue.access$000(EventQueue.java:101) at java.awt.EventQueue$3.run(EventQueue.java:666) at java.awt.EventQueue$3.run(EventQueue.java:664) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:675) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105) at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

  • merve

    Hello Tommi,thanks for sharing! i wonder if comments like “it works on some devices” are based on mobile OS? i tried it on galaxy ace and i received the following exception: Failed to connect; [10064] A socket operation failed because the destination host was down.
    But when i tried in on nokia 6220c, it works fine. so is this about android/symbian, if it is what should i change to make it work on android phone?