Your Ad Here

Wednesday, August 5, 2009

How to send file to mobile from computer using java application through bluetooth

Here is the source code for the sending files to mobiles from computer/pc using java application or j2me code through bluetooth as transmission medium.Many of us means amateur java and j2me programmer find it difficult to use bluetooth in java application as java development kit has no bluetooth library to use. As I have mentioned in my previous posts Bluecove is a J2SR-82 project meant for acessing bluetooth stack from java (java standard edition) .





So, for sending files from pc to mobile using java application through bluetooth. You must download Bluecove() and place it in both the runtime library extension folder of jre and jdk i.e "C:\Programs Files \Java\jre1.6.0\lib\ext" and "C:\Programs Files \Java\jdk1.6.0\jre\lib\ext" or the place where you have installed java under that find these two paths "jre1.6.0\lib\ext" and "jdk1.6.0\jre\lib\ext".

Before starting you must have bluetooth stack installed in your computer as mentioned in my previous post "Bluetooth Mobile Webcam - A Java & J2me based Project"


Change one thing in the code :

"File file = new File("D:/cmd.jpg");
InputStream is = new FileInputStream(file);
byte filebytes[] = new byte[is.available()];
is.read(filebytes);
is.close();"

Find this part in the code "File file = new File("D:/cmd.jpg")" and change the file path to your desired file path that you want to send to mobile.
eg: C:\test.txt

Now, compile this code and run it ....
Source Code Started:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

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.Connection;
import javax.microedition.io.Connector;
import javax.obex.ClientSession;
import javax.obex.HeaderSet;
import javax.obex.Operation;


/**
*
* Class that discovers all bluetooth devices in the neighbourhood,
*
* Connects to the chosen device and checks for the presence of OBEX push service in it.
* and displays their name and bluetooth address.
*
*
*/
public class BluetoothServiceDiscovery implements DiscoveryListener{
//object used for waiting
private static Object lock=new Object();
//vector containing the devices discovered
private static Vector vecDevices=new Vector();
//vector containing the services discovered
private static Vector vecServices=new Vector();
private static String connectionURL=null;

/**
* Entry point.
*/
public static void main(String[] args) throws IOException
{
BluetoothServiceDiscovery bluetoothServiceDiscovery=new BluetoothServiceDiscovery();
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
//find devices
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
System.out.println("Starting device inquiry...");
agent.startInquiry(DiscoveryAgent.GIAC, bluetoothServiceDiscovery);
try {
synchronized(lock){
lock.wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Device Inquiry Completed. ");
//print all devices in vecDevices
int deviceCount=vecDevices.size();
if(deviceCount <= 0){
System.out.println("No Devices Found .");
}
else{
//print bluetooth device addresses and names in the format [ No. address (name) ]
System.out.println("Bluetooth Devices: ");
for (int i = 0; i < devicecount; i++)
RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
System.out.println((i+1)+". "+remoteDevice.getBluetoothAddress());//+" ("+remoteDevice.getFriendlyName(true)+")");
}
}

// System.out.print("Choose the device to search for Obex Push service : ");
// BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));
// String chosenIndex=bReader.readLine();
// System.out.println(chosenIndex);

// int index=Integer.parseInt(chosenIndex);

// System.out.println(chosenIndex);

for(int j = 0; j < deviceCount; j++)
{
//check for obex service
RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(j);

UUID[] uuidSet = {new UUID("1105", true)};


int[] attrSet = {0x0100, 0x0003, 0x0004};
System.out.println("\nSearching for service...");

int transID = agent.searchServices(attrSet,uuidSet,remoteDevice,bluetoothServiceDiscovery);
System.out.println("Service Search in Progress ("+transID+")");
try {
synchronized(lock)
{
lock.wait();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}

//System.out.println("Service Discovery Completed. ");


System.out.println("Opening a connection with the server.... ");
// connection creation & sending file
try
{
Connection connection = Connector.open(connectionURL);
System.out.println("Connection obtained");

ClientSession cs = (ClientSession)connection;
HeaderSet hs = cs.createHeaderSet();

cs.connect(hs);
System.out.println("OBEX session created");

//System.out.println("Response code of the server after connect..." +hs.getResponseCode());

File file = new File("D:/cmd.jpg");
InputStream is = new FileInputStream(file);
byte filebytes[] = new byte[is.available()];
is.read(filebytes);
is.close();

hs = cs.createHeaderSet();
hs.setHeader(HeaderSet.NAME, file.getName());
hs.setHeader(HeaderSet.TYPE, "image/jpeg");
hs.setHeader(HeaderSet.LENGTH, new Long(filebytes.length));

Operation putOperation = cs.put(hs);
System.out.println("Pushing file: " + file.getName());
System.out.println("Total file size: " + filebytes.length + " bytes");

OutputStream outputStream = putOperation.openOutputStream();
outputStream.write(filebytes);
System.out.println("File push complete");

outputStream.close();
putOperation.close();

cs.disconnect(null);

connection.close();
}
catch(Exception e)
{
System.out.println("connection:"+e);
}
}


}
/**
* Called when a bluetooth device is discovered.
* Used for device search.
*/
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
//add the device to the vector
if(!vecDevices.contains(btDevice))
{
vecDevices.addElement(btDevice);
}
}
/**
* Called when a bluetooth service is discovered.
* Used for service search.
*/
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
/*if(servRecord!=null && servRecord.length>0)
{
connectionURL=servRecord[0].getConnectionURL(0,false);
System.out.println(connectionURL+"--"+servRecord);
}*/
for(int i = 0; i < servRecord.length; i++)
{
//vecServices=servRecord[i].getConnectionURL(0,false);
DataElement serviceNameElement = servRecord[i].getAttributeValue(0x0100);
String _serviceName = (String)serviceNameElement.getValue();
String serviceName = _serviceName.trim();
System.out.println(_serviceName);

if(serviceName.equals("OBEX Object Push"))
{

System.out.println("[client:] A matching service has been found\n");

try
{
connectionURL = servRecord[i].getConnectionURL(0,false);
System.out.println(connectionURL+"\n");
} catch (Exception e)
{
System.out.println("[client:] oops");
}
}
}


}
/**
* Called when the service search is over.
*/
public void serviceSearchCompleted(int transID, int respCode) {
/*synchronized(lock)
{
lock.notify();
}*/
String searchStatus = null;

if (respCode == DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE) {
searchStatus = "SERVICE_SEARCH_DEVICE_NOT_REACHABLE\n";
}
else if (respCode == DiscoveryListener.SERVICE_SEARCH_NO_RECORDS) {
searchStatus = "SERVICE_SEARCH_NO_RECORDS\n";
}
else if (respCode == DiscoveryListener.SERVICE_SEARCH_COMPLETED) {
searchStatus = "SERVICE_SEARCH_COMPLETED\n";
}
else if (respCode == DiscoveryListener.SERVICE_SEARCH_TERMINATED) {
searchStatus = "SERVICE_SEARCH_TERMINATED\n";
}
else if (respCode == DiscoveryListener.SERVICE_SEARCH_ERROR) {
searchStatus = "SERVICE_SEARCH_ERROR\n";
}

System.out.println("[client:] " + searchStatus);

synchronized(lock)
{
lock.notify();
}
}
/**
* Called when the device search is over.
*/
public void inquiryCompleted(int discType) {

switch (discType)
{
case DiscoveryListener.INQUIRY_COMPLETED :
System.out.println("INQUIRY_COMPLETED");
break;
case DiscoveryListener.INQUIRY_TERMINATED :
System.out.println("INQUIRY_TERMINATED");
break;
case DiscoveryListener.INQUIRY_ERROR :
System.out.println("INQUIRY_ERROR");
break;
default :
System.out.println("Unknown Response Code");
break;
}
synchronized(lock)
{
lock.notify();
}
}//end method
}//end class




Bookmark and Share

22 comments:

Anonymous said...

Its working .. thanks i have spend days for doing this...:D

Biti said...

k dude keep visiting and you will get many new stuffs

choke911 said...

Awesome stuff, thanks Biti.
But the code above have a few problems.

1>> import java.io.File;
import java.io.FileInputStream;

These 2 lines are marked red in Netbeans. J2ME doesn't have these 2 classes. How did you manage to use it?

2>> File file = new File("D:/cmd.jpg");
InputStream is = new FileInputStream(file);

Netbeans says "cannot find symbol" for File. It should be fixed if no. 1 is fixed.

3>> The FOR loops are incomplete. May be they weren't copied to clipboard when you were copying from your editor.

It will be of great help if you provide some download link for the code rather than pasting it here like you did in the webcam project.

Anyway, thanks a lot for sharing the knowledge.
Waiting for your reply...

choke911 said...

Oops, my mistake..the whole thing in this page is about sending from PC to mobile and not the other way round.
Anyway, you do need to complete the FOR loops.
Thanks again for sharing, keep up the good works.

Biti said...

There might be some mistake in the code, Sorry for that. I will correct the problem and post the code again soon.

Anonymous said...

IT is userful, thank a lot.
But I don't see code in j2me read file, please help me!!

Juan Carlos Garcia Amaral said...

Hi!
i´m making a programm, and i took this program, ich want to send a simple stream from server to client and from client to server.
For example, when i try to send this stream, i write:
else if (c==send){
form.append(\nCLIENTE>>>" +TextField.getString());

try{
out = new DataOutputStream (conn.openDataOutputStream());
out.writeUTF("SERVIDOR>>>" + textField.getString());
out.flush();
}
catch(IOException ex){}
}
In server and client i have not the same but a little bit similar.
But i don´t know what i´m doing wrong.
Someone can help me

Anonymous said...

hi..ive tried ur code but it went wrong because in netbeans v. 6.01 ,pakages about the bluetooth were not available. do you have sum suggestions wat environment is it runnable? oxalis_garden88@yahoo.com

Juan Carlos Garcia Amaral said...

Hi,
I solved that, thank you.But now i have two new problems,
How can i know the bluetooth signal strenght?
and i´ve try to improve the server, i´m making a chat application, but i´ve problems with the distance between server and mobile. I can make that just at 5 mts. but in the theorie i can until 100mts.

Juan Carlos Garcia Amaral said...

for your question, netbeans support bluetooth applications, for j2me. To make the connection between java and j2me you need bluecove.

Juan Carlos Garcia Amaral said...

Somebody knows if i could use de.avetana.bluetooth.hci.rssi? , i want to measure the signal strength from bluetooth signal.
I´ve read that bluecove package supports HCI,
RFCOMM, OBEX, etc. See bluecove Stack.
But when i´m programming that thing i don´t found that package, HCI (RSSI)
i want use getRssi(); but i can´t,

Somebody Knows how i can do that?

Juan Carlos Garcia Amaral said...

For the comment before,
Is that (HCI) only for Linux?

ransa said...

Awesome code, thanks Bish.
But the code above have a few problems.
The 'for' loop is incomplete ,thats why i am having runtime problem(ArrayIndexOutOfBoundsException).
Can u please post the limits of the loop ASAP?
Its very urgent.
Thanx

Biti said...

@Juan Carlos Garcia Amaral: I have no idea about (HCI), but i will try to solve your problem

Biti said...

@ransa: today itself i will correct the error means complete the for loop and post it.

Biti said...

CODE UPDATED. ALL ERRORS ARE REMOVED.

Anonymous said...

thanks!!!!
can u please send me the java code for voice transfer or video conferencing vi bluetooth between two pc
my email is
gupta.krishna89@gmail.com

Weltmeisterbräu said...

@biti,
i see you compile the file, nice?
what exaclty are you doing?
I'm one more time with the project, i made a simple communication over bluetooth RFCOMM,
and OBEX.
Now i will use java.mail, at the moment i know that it is possible with javax.mail and use TCP.to my pc and then send it to mobile like sms.
And finally i want to communicate with voice, i know that is possible, but the API jsr82 doesn´t support that protocol. If you know something about it, please tell me. Maybe i can help you with you application.
greetings,
jc

Karjol said...

Biti,

Thanks so much for this code. It really helped me

Regards,
Karjol

Anonymous said...

hello sir,i tried to execute this code in java but it is showing error in for loop..i tried in J2ME also but it shows lot of error..can u please help me..and post the procedure to execute the code.please very urgent..since i'm new to this J2ME

Anonymous said...

well biti. a real great help was found here... i am doin a similar project... and i was stuck in selecting the protocol.... thanks a lot......i will follow up with this blog..... and one last thing... this code has one for loop missing still i think as i got that error also the implimentation has been done twice.... well i am new to java so i dont know whether its wrong or right.... anyways tnx a lot...

Anonymous said...

hi,i tried this code in eclipse,but its showing lots of errors...can anyone please help me....

u can also contact me in gmail-sandeshk779@gmail.com

PLEASE HELP....

Thanks in advance....

Post a Comment

Type here your comments