Transfer String from android to pc via bluetooth - android

Since many days i am going through many examples and questions related to my issue but nothing helps!
Aim
two way communication between pc(windows) and android (like passing msg to pc and acknowledgement from pc)
What i have done till now
I am able to send String to pc(windows) from my android device using bluetooth.
here is the code i used
private String sendFile(String mac_address, String device_name) {
// TODO Auto-generated method stub
String result="";
btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdapter.getRemoteDevice(mac_address);
Log.d("BT_SENDING_FILE",device_name+" "+mac_address);
try {
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
btSocket = (BluetoothSocket) m.invoke(device, 1);
if(!btSocket.isConnected()){
Log.d(" is connected Status",""+btSocket.isConnected());
// device.createInsecureRfcommSocketToServiceRecord(UUID);
}
btAdapter.cancelDiscovery();
try{
btSocket.connect();
}catch(IOException e){
btSocket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
btSocket.connect();
Log.d("fall back","in catch clause");
}
byte[] msgBuffer = stringToSend.getBytes();
outStream = btSocket.getOutputStream();
outStream.write(msgBuffer);
if (outStream != null) {
outStream.flush();
}
result = "sent";
outStream.close();
btSocket.close();
Log.d("BLUETOOTH","Closing Socket");
} catch (Exception e) {
System.out.println(e);
Log.d("BLUETOOTH","exception while sending through bluetooth");
result = "failed";
e.getLocalizedMessage();
} finally{}
return result;
}
this is running good without any problem.
Problem
But i am not able to receive any String from pc to android device. I have tried many things
I have tried this
BluetoothSocket socket = null;
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
while (true) {
try {
// Creating a new listening server socket
Log.d("BT", ".....Initializing RFCOMM SERVER....");
mmServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord("Bluetooth", MY_UUID);
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d("Socket","listening...");
socket = mmServerSocket.accept(120000);
} catch (Exception e) {
}
try {
Log.d("Socket", "Closing Server Socket.....");
mmServerSocket.close();
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
Log.d("BT","IO stream init");
DataInputStream mmInStream = new DataInputStream(tmpIn);
DataOutputStream mmOutStream = new DataOutputStream(tmpOut);
// use the Input Stream to take the string from the client whoever is connecting
//similarly use the output stream to send the data to the client
StringBuilder sb = new StringBuilder();
while((ch = mmInStream.read())!= -1)
sb.append((char)ch);
String res = sb.toString();
Log.d("BT",res);
tv_response.setText(res));
} catch (Exception e) {
//catch your exception here
e.printStackTrace();
Log.d("Exception","some thing went wrong");
e.getLocalizedMessage();
}
}
}
I am using Blue Cove in windows. I HAVE GONE THROUGH BLUETOOTH CHAT SAMPLE PROJECT but dont understand any thing
your help is appreciated
thank you

i tried following code and it was successful. it may help you
BluetoothSocket socket = null;
while (true) {
try {
Log.i(ACCEPT_TAG, "Listening for a connection...");
socket = mServerSocket.accept();
Log.i(ACCEPT_TAG, "Connected to " + socket.getRemoteDevice().getName());
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
try {
// Read the incoming string.
String buffer;
DataInputStream in = new DataInputStream(socket.getInputStream());
buffer = in.readUTF();
Intent i = new Intent(MESSAGE_RECEIVED_INTENT);
i.putExtra("Message", String.format("%s", buffer));
Log.d("BT response is",buffer);
c.sendBroadcast(i);
} catch (IOException e) {
Log.e(ACCEPT_TAG, "Error obtaining InputStream from socket");
e.printStackTrace();
}
try {
mServerSocket.close();
} catch (IOException e) { }
break;
}
}
Be sure that your device is visible to all i.e scan mode is BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE
else use this code
public void requestBTDiscoverable() {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivityForResult(i, REQ);
int result = 0;
this.onActivityResult(REQ, result, i);
Log.i(TAG, "Bluetooth discoverability enabled");
}

Related

Udp not receiving data from server (android client, pc java server)

i am making a chat application for android using UDP.
Everything works fine in lan devices, I can send and receive messages from client and from server.
When i connect to an other network with my android, i can send messages, the server receives them but the response is never received on android.
Client Receive code
Runnable periodicTask = new Runnable() {
public void run() {
// Invoke method(s) to do the work
System.out.println("Waiting for data");
byte[] receiveData = new byte[2028];
byte[] sendData = new byte[2028];
boolean portTaken=false;
DatagramSocket serverSocket=null;
ServerSocket socket = null;
try {
socket = new ServerSocket(6667);
} catch (IOException e) {
System.out.println("ERRORRRRRRRRRRRRRR");
} finally {
if (socket != null)
try {
socket.close();
serverSocket= new DatagramSocket(6667);
} catch (IOException e) { e.printStackTrace(); }
}
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
try {
serverSocket.receive(receivePacket);
System.out.println("GOT THEM!");
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayInputStream in = new ByteArrayInputStream(receiveData);
ObjectInputStream is = null;
try {
is = new ObjectInputStream(in);
} catch (IOException e) {
e.printStackTrace();
}
Data student = null;
try {
student = (Data) is.readObject();
l.add(student.toString());
mHandler.sendEmptyMessage(0);
System.out.println(student);
serverSocket.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
Server Send Code
for (DatagramPacket packet:clients){
if (!packet.getAddress().equals(receivePacket.getAddress())){
System.out.println("current ip address " + receivePacket.getAddress());
System.out.println("Sending to " + packet.getAddress());
DatagramSocket s = new DatagramSocket();
InetAddress local =packet.getAddress();//editTextAddress.getText().toString());//InetAddress.getByName("192.168.1.74");
System.out.println(local.toString());
//int msg_length =student.//sentence.length();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outputStream);
os.writeObject(student);
byte[] data2 = outputStream.toByteArray();
int msg_length =data2.length;
DatagramPacket p = new DatagramPacket(data2, msg_length, local,
6667);
s.send(p);
s.close();
}
What might be the case ?
Thank you for your time

Android tcp socket connection slow

I have set up a server on my computer in java, and the client is my android phone.
I am trying to simulate the mouse behavior in my app but the problem is even though at the first minutes everything runs smoothly, in the end there is a huge delay between client and server.
Server code
try {
System.out.println(InetAddress.getLocalHost());
serverSocket = new ServerSocket(4444); // Server socket
serverSocket.setReceiveBufferSize(10000);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
try {
clientSocket = serverSocket.accept(); // accept the client connection
System.out.println("connection initiated");
DataInputStream din = new DataInputStream(clientSocket.getInputStream());
DataOutputStream dout= new DataOutputStream(clientSocket.getOutputStream());
/* do my things here */
din.close();
dout.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading "+ex);
}
Client code
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
//Inet4Address.getLocalHost().toString(); //InetAddress.getLocalHost().getHostAddress().toString();
System.out.println(dstAddress);
socket = new Socket(dstAddress, dstPort);
socket.setSendBufferSize(10000);
DataInputStream din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
dout.writeUTF(kappa);
response = "sent to server";
String msg = din.readUTF();
response += msg;
din.close();
dout.close();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = e.toString();
}
return null;
}
(kappa is a global string that i modify each time.)
What might be the case?
Problem is solved, i changed to udp connection and now there is no delay

how to send data from Group owner to client with wifi p2p

I tested many ways and finally asked this question. as many of articles mentioned in wifi-direct all clients know group owner's IP and can use this ip to send a message and group owner will save clients ip address. but I can't send a message from group owner to client like that client sent first time. I faced with this error's:
first:
failed to connect to /192.168.49.24 (port 8988) after 5000ms: isConnected failed:
EHOSTUNREACH (No route to host).
after change code:
first error + bind failed: EADDRINUSE (Address already in use).
My AsyncTask to retrieve :
#Override
protected String doInBackground(Void... params) {
ServerSocket serverSocket = null;
Socket client = null;
DataInputStream inputstream = null;
try {
serverSocket = new ServerSocket(8988);
client = serverSocket.accept();
inputstream = new DataInputStream(client.getInputStream());
String str = inputstream.readUTF();
String IP = client.getInetAddress().toString();
serverSocket.close();
return IP+"+"+str;
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}finally{
if(inputstream != null){
try{
inputstream.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(client != null){
try{
client.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(serverSocket != null){
try{
serverSocket.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
}
}
and my IntentService to send messages:
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_IP)) {
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Log.e("DAVUD","Host:"+ host);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Log.e("DAVUD","Port:"+ port);
DataOutputStream stream = null;
try {
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
stream = new DataOutputStream(socket.getOutputStream());
String str = intent.getStringExtra("message");
stream.writeUTF(str);
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
and some other codes I tested... There is another question asked same this but not answered(android-wifi-direct-how-to-send-data-from-group-owner-to-the-clients) this project based on wifiDirectDemo Simple. Please help I really need it.
After one year I sew my question again. the problem was not about wifi or connection. it's about string parsing. where a line in doInBackground is:
return IP+"+"+str
and in onPostExecute I parsed and get ip from returned string; but parse code was not correct. so returns:
192.168.49.24
instead of:
192.168.49.241
where two of them is valid ips I am not thought parse logic had problem. I changed code and used String[] instead of String.

Pdf to bluetooth Printer issue

I am trying to send PDFs file to Bluetooth printer. I have established the connection successfully but the printer is not printing the file in the proper format / formation.
Here is the code that I am using:
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
Log.d("UUID Before Socket is created", MY_UUID.toString());
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (Exception e) {
e.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
myBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
socketConnected = true;
} catch (Exception connectException) {
// Unable to connect; close the socket and get out
connectException.printStackTrace();
Log.i("Connection Message", "Couldn't connect at first go.");
try {
mmSocket =(BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mmDevice,1);
mmSocket.connect();
socketConnected = true;
Log.i("Connection Message", "Connected using second method.");
} catch (Exception closeException) {
closeException.printStackTrace();
try {
mmSocket.close();
socketConnected = false;
} catch (IOException ex) {
ex.printStackTrace();
}
}
return;
}
try{
tmpOut = mmSocket.getOutputStream();
File file = new File(filePath);
Uri uri = Uri.fromFile(file);
BufferedInputStream bis = new BufferedInputStream(getContentResolver().openInputStream(uri));
//OutputStream os = tmpOut;
try {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = bis.read(buffer)) != -1) {
tmpOut.write(buffer, 0, len);
}
} finally {
bis.close();
tmpOut.flush();
tmpOut.close();
mmSocket.close();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Here is the output of a pdf file.
P.s the pdf is in Italian language.

unable to connect bluetooth device

I am trying to connect bluetooth device and want to send data to that device and also want to receive data from that device.
To achieve this I follow android developer bluetooth document but seems I unable to connect another device because while connecting it's throwing following exception.
09-13 13:27:56.913: I/BluetoothConnect(2980): Connect exception:-java.io.IOException: [JSR82] connect: Connection is not created (failed or aborted).
Steps which I follow.
Enabling Bluetooth
Intent turnOnIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Getting Bluetooth Paired Device
Set<BluetoothDevice> bondSet = myBluetoothAdapter.getBondedDevices();
ArrayList<HashMap<String, String>> bondedhDevicesList = new ArrayList<HashMap<String, String>>();
for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) {
BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next();
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", bluetoothDevice.getName());
map.put("address", bluetoothDevice.getAddress());
bondedhDevicesList.add(map);
}
Getting UUID of device
bluetoothDevice =
myBluetoothAdapter.getRemoteDevice(address);
// min api 15 !!!
Method m;
try {
m = bluetoothDevice.getClass().
getMethod("fetchUuidsWithSdp", (Class[]) null);
m.invoke(bluetoothDevice, (Object[]) null );
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connecting to device
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
public ConnectThread(BluetoothDevice device, String uuid, BluetoothAdapter mBluetoothAdapter) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
this.mBluetoothAdapter = mBluetoothAdapter;
mmDevice = device;
Method m;
try {
mBluetoothAdapter.cancelDiscovery();
mmSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
mmSocket = (BluetoothSocket) m.invoke(device, 1);
} catch (IOException | IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
// TODO Auto-generated catch block
Log.i("BluetoothConnect", e.toString());
e.printStackTrace();
}
//mBluetoothAdapter.cancelDiscovery();
//socket.connect();
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Constants.globalSocket = mmSocket;
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
Log.i("BluetoothConnect", "Connect exception:-"+connectException.toString());
try {
mmSocket.close();
} catch (IOException closeException) {
Log.i("BluetoothConnect", "close exception:-"+closeException.toString());
}
return;
}
}
But while connecting then i am getting that exception.
5. Writing to device.
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
CreatePacket.mHandler.obtainMessage(MESSAGE_READ , bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.i("ConnectedThread", "while receiving data:-"+e.toString());
break;
}
}
}
public void write(byte[] bytes) {
Log.i("ConnectedThread", "data while writing:-"+bytes.toString());
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.i("ConnectedThread", "while writing data to bluetooth:-"+e.toString());
}
}
If I still try to write then data then I am getting following exception.
Please give me any hint or reference.
09-13 13:48:55.079: I/ConnectedThread(2980): while writing data to bluetooth:-java.io.IOException: socket closed
I am stuck on this from last three day but still not getting any solution.
The best way is to refer the sample chat application provided by the Android. That has covered all necessary tasks like list out available devices, establish connection, send data and receive, etc. U can get that and refer.
https://android.googlesource.com/platform/development/+/eclair-passion-release/samples/BluetoothChat
Here is a sample code which I am using to connect to my Bluetooth module..
public class OpenBluetoothPort extends AsyncTask<String, Void, BluetoothSocket> {
private final UUID SPP_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter mBluetoothAdapter;
private OnBluetoothPortOpened mCallback;
private BluetoothSocket mBSocket;
public interface OnBluetoothPortOpened {
public void OnBluetoothConnectionSuccess(BluetoothSocket socket);
public void OnBluetoothConnectionFailed();
}
public OpenBluetoothPort(Context context, OnBluetoothPortOpened callback) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mCallback = callback;
}
#Override
protected BluetoothSocket doInBackground(String... params) {
if(mBluetoothAdapter.isEnabled()) {
try {
for(BluetoothDevice bt: mBluetoothAdapter.getBondedDevices()) {
if(bt.getName().equalsIgnoreCase(params[0])) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bt.getAddress());
mBluetoothAdapter.cancelDiscovery();
mBSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
mBSocket.connect();
return mBSocket;
}
}
} catch(IOException e) {
if(mBSocket != null) {
try {
mBSocket.close();
} catch (IOException e1) {
Log.i("Bluetooth Close Exception","Error in closing bluetooth in OpenBluetoothPort.class");
e1.printStackTrace();
}
mBSocket = null;
}
Log.i("Bluetooth Connect Exception","Error in connecting in OpenBluetoothPort.class");
e.printStackTrace();
return null;
}
}
return null;
}
#Override
protected void onPostExecute(BluetoothSocket result) {
super.onPostExecute(result);
if(result != null && result.isConnected()) {
mCallback.OnBluetoothConnectionSuccess(result);
} else {
mCallback.OnBluetoothConnectionFailed();
}
}
}

Categories

Resources