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.

36 Responses to “Sending files to mobile phone using Bluetooth and OBEX”

Pages: [1] 2 » Show All

  1. 1
    Irving Says:

    Hi Tommi,

    Have you tried using J2ME bluetooth JSR-82 to receive the file? When I look at it, it seems that it needs it’s own service.

    Regards,

    Irving

  2. 2
    elan Says:

    run:
    LOG: Start discovery
    ERROR: Error in main: Unable to load HCIManager. org.javabluetooth.stack.hci.HCIException: BluetoothStack not initalized.
    LOG: Discovery end

    how to overcome the above error with bluetoothpresence

  3. 3
    elan Says:

    hai everybody…….i have removed HCI Exception
    i remove the JavaComm library from (www.javabluetooth.org), i used the Java Communication API from Sun (comm2.0.3) and now the demo works fine….

    one more problem…
    now it shows
    LOG: Start discovery
    ERROR: Error in main: Bluetooth Device is not ready
    LOG: Discovery end

    but using IVT bluesoliel GUI, its working,but with the demo app,it shows the log like this….how to over come

    tks in advance
    elan78in@yahoo.com

  4. 4
    elan Says:

    I am using Bluesoleil driver and it is working fine.When i run the samplw tih bluecove…it shows the following error.

    run:
    LOG: Start discovery
    BlueCove version 2.0.3 on widcomm
    ERROR: Error in main: Bluetooth Device is not ready
    LOG: Discovery end

    Please help me…how to set the bluesoleil as my default stack in bluecove….I think i hav to pass very few steps to get PC to Mobile chat via bluetooth. elan8in@yahoo.com

    urs
    elan

  5. 5
    elan Says:

    Just today i have overcome this error…..

    Steps:
    1.Add a new file with ur Project named “bluecove.stack”
    2.Place the content “Bluesoleil” in that file.
    3.Now execute ur program.

    Now it displays like
    compile:
    run:
    BlueCove version 2.0.3 on bluesoleil
    ITLAB-29

    Here ITLAB-29 is my system Bluetooth Name

    Thanks Tommi
    By
    elan elan8in@yahoo.com

  6. 6
    elan Says:

    hi tommi,

    may i get the sample code for PC Bluetooth chat….(Using L2Cap)
    i have already done it for mobile to mobile…

    Tks in advance
    Urs
    elan78in@yahoo.com

  7. 7
    elan Says:

    Is it possible to make L2cap chat woth bluecove…..?
    I have done for mobile….Is it possible to connect the Mobile Chat application with PC chat(BTooth) application

    elan78in@yahoo.com

  8. 8
    Goncalo Says:

    Hi,

    I cant compile this code because of a class (GroupLayout) can you put the jar file in here.

    Thx a lot

  9. 9
    Tommi Laukkanen Says:

    @Goncalo: GroupLayout is in JDK 1.6.

  10. 10
    Goncalo Says:

    thx, i already resolve that problem

    i have another maybe you can help me
    how i can connect the bluetooth(PC) to my simulate application (sun java wirelles toolkit) ?

  11. 11
    wong Says:

    Hi everyone, i got a sample code of bluetooth chat application for mobile to mobile, but it unable to send files such as picture…
    so anyone got sample code of bluetooth chat application that can send and receive picture? anyone can share the code with me?

    thx in advance^^

  12. 12
    Nazrul Amin Says:

    Hello Mate, this is to the publisher of this work.

    I have tried to download and run both of your examples, eg this one and the bluettoh presence one. I am unable to compile any of your sources? as its looking for something eg import com.substanceofcode.logging.

    Please help me as I need to know how your code works?

    Thanks

  13. 13
    ahmad Says:

    Hi :
    why it doesnt find active bluetooth devices ? i think because it doesnt search services. what should i do?

  14. 14
    [kazmer] Says:

    Tommi: thank you very much for the bluetooth examples, they really help me getting started with bluetooth programming

    may i point out two little errors in your code?
    the first is also the answer to ahmad’s question:
    you forgot to add the newly created ListItem to the model
    the second is a little design flaw:
    if you click the refresh button twice, the second click gives a nice exception
    it can be avoided, by disabling the button in its actionlistener, and re-enabling it after the inquiry

    here is my version of the methods
    ps: again, thanks a lot, and keep up the good work!

    void refreshList () {
    refreshButton.setEnabled(true);

    ApplicationContext context = ApplicationContext.getInstance();
    deviceList.removeAll();
    DefaultListModel model = new DefaultListModel();
    List devices = context.getDevices();

    if(devices != null) {
    for(RemoteDevice device : devices) {
    try {
    String friendlyName = device.getFriendlyName(false);
    ListItem item = new ListItem(device, friendlyName);
    model.addElement(item);
    } catch(IOException ex) {
    Logger.getLogger(ApplicationFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
    }
    deviceList.setModel(model);
    repaint();
    }

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {
    BluetoothBrowser browser;
    try {
    browser = new BluetoothBrowser(this);
    browser.inquiry();
    refreshButton.setEnabled(false);
    } catch(BluetoothStateException ex) {
    Logger.getLogger(ApplicationFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

    }

  15. 15
    Tommi Laukkanen Says:

    kazmer: Thanks for pointing out the improvements and providing the code listing.

  16. 16
    Ali Jin Says:

    Hey Tommi i got to say hats off to you if it werent for you I would be suspended in mid air mentally trying to decipher some of this stuff….but I have a slight problem with this one I cant seem to get my devices to show on the screen now i do know that Kazmer said something about adding the ListItem to the Model…what model would that be … really appreciate thanks mate.

  17. 17
    Tommi Laukkanen Says:

    @Ali Jin: Check out the code that Kazmer posted in his comment. The model is the DefaultListModel:

    DefaultListModel model = new DefaultListModel();

  18. 18
    shzewei Says:

    hi all, i am new in bluetooth programming.
    may someone teach me how to solve the problem i facing?
    the error msg come out when i press the upload file button
    thanks
    error msg:

    Exception: Device service not discovered
    java.io.IOException: Device service not discovered
    at com.intel.bluetooth.BluetoothStackBlueSoleil.connectionRfOpenClientConnection(BluetoothStackBlueSoleil.java:348)
    at com.intel.bluetooth.BluetoothRFCommClientConnection.(BluetoothRFCommClientConnection.java:33)

  19. 19
    Ali Says:

    Hey Tommi, M back i figured i missed to check the code properly and thats why I couldnt really see the devices feels really dumb at one point but past few days been trying to get the files to send and it doesnt seem to work at all i keep getting this massive errors

    init:
    deps-jar:
    compile:
    run:
    BlueCove version 2.1.0 on widcomm
    Exception: Failed to connect
    javax.bluetooth.BluetoothConnectionException: Failed to connect
    at com.intel.bluetooth.BluetoothStackWIDCOMM.connectionRfOpenClientConnectionImpl(Native Method)
    at com.intel.bluetooth.BluetoothStackWIDCOMM.connectionRfOpenClientConnection(BluetoothStackWIDCOMM.java:635)
    at com.intel.bluetooth.BluetoothRFCommClientConnection.(BluetoothRFCommClientConnection.java:37)
    at com.intel.bluetooth.MicroeditionConnector.openImpl(MicroeditionConnector.java:387)
    at com.intel.bluetooth.MicroeditionConnector.open(MicroeditionConnector.java:162)
    at javax.microedition.io.Connector.open(Connector.java:83)

    so i tried to check within the Bluecove jar file if the classes were there and with netbeans its nt possible to open the class files
    so the search and the listing is fine but when it come to uploading a file then i get a runtime so if you got any idea on why m getting the errors would be great help
    thnx

  20. 20
    Ali Says:

    Hi (for information purposes)

    The Problem with my previous error is that there is a phone (SE W810) issue and not a BlueCove API issue so if you are testing it on that phone you might encounter this error otherwise try using a different phone

    regards

  21. 21
    Alibi Says:

    Hi guys , upon uploading files I am getting errors like Device service not discovered
    What to do ?

  22. 22
    mark Says:

    hi all,

    at first thankx for good posting. its really useful for me.

    fine but friends i want same kind of application , hope u will help me

    i want source of file transferring and chating application.

    on any mobile-mobile or pc-mobile

    plz help me

    send me some sample atleast on my mail id – markwilson1@mail.com
    or m.wilson2913@gmail.com

  23. 23
    Tommi Laukkanen Says:

    @mark: Check out the Sony Ericsson site for Bluetooth chatting samples:
    http://developer.sonyericsson.com/site/global/techsupport/tipstrickscode/symbian/p_symbian_0501.jsp

  24. 24
    Finn Says:

    thanks tommi, can we send a jar file instead of image type?

    and do you know how to send jar to mobile phone automatically with this bluetooth code (without selecting which remote device) ?

  25. 25
    Mary Says:

    Hi guys , fist of all thank you so much for the code. I’m writing because I have a problem when I try to upload a file, the exception said:

    Device service not discovered

    What can I do to solve this problem?

Pages: [1] 2 » Show All

Leave a Reply