Service discovery failed android bluetooth - android

I am developing a code to communicate to custom bluetooth circuit from Micromax Tab. Till socket creation it works fine. But when i try to connect it fails saying either Service discovery failed or host is down. I tried all the possible posts referring to this topic mentioning same problem. But end up getting same errors. I tried to change UUID but nothing works. Any clues?
Below is my code:
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth not found",Toast.LENGTH_LONG).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
if(device.getName().equals("linvor"))
{
mmDevice = device;
Toast.makeText(this, "Name: " + device.getName() + " And Address: " + device.getAddress(),Toast.LENGTH_LONG).show();
}
}
}
mBluetoothAdapter.cancelDiscovery();
BluetoothSocket tmp = null;
// UUID uuid = UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");
// MY_UUID is the app's UUID string, also used by the server code
// tmp = mmDevice.createRfcommSocketToServiceRecord(uuid);
Method m = null;
try {
m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
try {
tmp = (BluetoothSocket) m.invoke(mmDevice, 1);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
}
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(mmDevice, 1);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), "Created socket",Toast.LENGTH_LONG).show();
mmSocket = tmp;
mBluetoothAdapter.cancelDiscovery();
Toast.makeText(getBaseContext(), "Discovery cancelled",Toast.LENGTH_LONG).show();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Toast.makeText(getBaseContext(), "Connected",Toast.LENGTH_LONG).show();
} catch (IOException e1) {
// Unable to connect; close the socket and get out
Toast.makeText(getBaseContext(), e1.getMessage(),Toast.LENGTH_LONG).show();
try {
mmSocket.close();
} catch (IOException e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
}
}

You are using this one to send image...
#Override
protected void onPostExecute(Void result) {
if(selectedImageURI!=null)
{
ContentValues values = new ContentValues();
values.put(BluetoothShare.URI, selectedImageURI.toString());
Toast.makeText(getBaseContext(), "URi : " + selectedImageURI,
Toast.LENGTH_LONG).show();
values.put(BluetoothShare.DESTINATION, addressPairedDevice);
values.put(BluetoothShare.DIRECTION,
BluetoothShare.DIRECTION_OUTBOUND);
Long ts = System.currentTimeMillis();
values.put(BluetoothShare.TIMESTAMP, ts);
getContentResolver().insert(BluetoothShare.CONTENT_URI,
values);
}
BluetoothShare.java is in the link
How to send file using bluetooth on android programatically?
How to send file from Android device to other device through Bluetooth by code

Related

How to make a Bluetooth SPP connection process more reliable?

We are about to release the new version of our software, and for the version afterward, our goal is to make the connection process for our Bluetooth SPP connections more reliable. We use the RN42 module in our products, and currently, at times it may take more than one try to connect to our boards.
Here is my current code:
class ConnectThread extends Thread {
BluetoothDevice mDevice;
public ConnectThread(BluetoothDevice device) throws SecurityException, NoSuchMethodException {
mDevice = device;
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
btSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e("Error", "Could not create socket!");
}
}
public void cancel() {
interrupt();
try {
Log.i("Treadmill", "in connect thread cancellation");
btSocket.close();
} catch (IOException localIOException) {
Log.e("Treadmill", "exception + " + localIOException.getMessage());
}
}
public void run() {
btAdapter.cancelDiscovery();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("whatever", "InterruptedException: " + e.getMessage(), e);
}
try {
btSocket.connect();
Log.i("Treadmill", "After Connect");
} catch (IOException ioe) {
Log.i("Treadmill", "Trying Fallback");
try {
Method m;
try {
btSocket.close();
m = mDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class});
btSocket = (BluetoothSocket) m.invoke(mDevice, 1);
Thread.sleep(500);
btSocket.connect();
} catch (IllegalArgumentException e) {
Log.e("whatever", "IllegalArgumentException: " + e.getMessage(), e);
} catch (IllegalAccessException e) {
Log.e("whatever", "IllegalAccessException: " + e.getMessage(), e);
} catch (InvocationTargetException e) {
Log.e("whatever", "InvocationTargetException: " + e.getMessage(), e);
} catch (NoSuchMethodException e) {
Log.e("whatever", "NoSuchMethodException: " + e.getMessage(), e);
} catch (InterruptedException e) {
Log.e("whatever", "InterruptedException: " + e.getMessage(), e);
}
} catch (IOException ioe2) {
Log.e("Treadmill", "Failed to connect to Bluetooth device: " + ioe2.getMessage());
eventHandler.obtainMessage(MESSAGE_ERRORCONNECT, 0, 0, getResources().getString(R.string.connerr) + ": " + ioe2.getMessage()).sendToTarget();
try {
btSocket.close();
} catch (IOException localIOException2) {
Log.e("Error", "IO Exception!");
}
return;
}
}
eventHandler.obtainMessage(MESSAGE_CONNECT, 0, 0, "").sendToTarget();
synchronized (this) {
connectThread = null;
}
manageConnectedSocket(btSocket);
}
}
Even with the fallback to reflection the connection intermittently fails on some devices. I get the following error:
find_rfc_slot_by_id unable to find RFCOMM slot id: XX (XX being a number that increments on each attempted connection).
followed by this:
Failed to connect to Bluetooth device: read failed, socket might closed or timeout, read ret: -1
Does anyone know how to avoid these errors.
Interestingly, for comparison. I am testing on two tablets. One tablet, the Samsung Galaxy Tab 4 seems to work extremely well, while another, the Astro Tab A10, seems to be a bit more intermittent unless you wait several seconds between connecting and disconnecting.
For more reliable connection means even app was closed, Bluetooth should be keep connected in the background.
Below is the working solution I followed in my app to keep Bluetooth connection background.
First create a class which extends service, because service runs in the background even app closed until you call stopService or stopSelf methods
while starting BluetoothService class pass Bluetooth Mac address to connect and run in the background.
Sample code:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null){
String deviceg = intent.getStringExtra("bluetooth_device");
if (deviceg != null){
connectToDevice(deviceg);
}
}
return START_STICKY;
}
Below is the connect to device method which identifies mac Address into Bluetooth Device.
public synchronized void connectToDevice(String macAddress){
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddress);
if (mConnectedThread != null){
mConnectedThread.cancel();
mConnectedThread = null;
}
mConnectThread = new ConnectBtThread(device);
toast("connecting");
mConnectThread.start();
}
This is my Thread class inside BluetoothService which runs in a separate thread
Code:
private class ConnectBtThread extends Thread{
private final BluetoothSocket mSocket;
private final BluetoothDevice mDevice;
public ConnectBtThread(BluetoothDevice device){
mDevice = device;
BluetoothSocket socket = null;
try {
socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(B_UUID));
} catch (IOException e) {
e.printStackTrace();
}
mSocket = socket;
}
#Override
public void run() {
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
try {
mSocket.connect();
Log.d("service","Bluetooth one running (connected)");
} catch (IOException e) {
try {
mSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
connected(mSocket);
}
public void cancel(){
try {
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It works perfectly fine for our app.
If you want to access service methods bind this service to your activity

Send sms in pdu mode in Android

I am new in Android.
I want to send a sms in pdu mode and i found this code, but some class doesn't Support in android studio (Bold Lines). Can anyone help me ?
private void sendsmsBypdu(String phoneNumber,String message) {
int size;
Field f;
Log.d(TAG,"Retrieving phone instance ...");
ContactsContract.CommonDataKinds.Phone phone = **PhoneFactory.getDefaultPhone();**
/* Get IccSmsInterfaceManager */
Log.d(TAG,"Retrieving SmsInterfaceManager ...");
**IccSmsInterfaceManager ismsm = getIccSmsInterfaceManager();**
try {
Log.d(TAG,"Retrieving mDispatcher ...");
**f = IccSmsInterfaceManager.class.getDeclaredField("mDispatcher");**
f.setAccessible(true);
SmsManager sms_smg = (SmsManager)f.get(ismsm);
Log.d(TAG, "Formatting class 0 SMS ...");
byte[] b = new byte[0];
SmsMessage.SubmitPdu pdus = SmsMessage.getSubmitPdu(null, phoneNumber, message,false);
/* change class to Class 0 */
size = (int)pdus.encodedMessage[2];
size = (size/2) + (size%2);
pdus.encodedMessage[size+5] = (byte)0xF0;
/* send raw pdu */
Log.d(TAG,"Sending SMS via sendRawPdu() ...");
try
{
/* Android 2.2 -> 4.0.* */
Method m = SmsManager.class.getDeclaredMethod("sendRawPdu", b.getClass(), b.getClass(), PendingIntent.class, PendingIntent.class);
m.setAccessible(true);
m.invoke(sms_smg, pdus.encodedScAddress, pdus.encodedMessage, null, null);
}
catch(NoSuchMethodException e)
{
/* Android 4.1.2 */
Method m = SmsManager.class.getDeclaredMethod("sendRawPdu", b.getClass(), b.getClass(), PendingIntent.class, PendingIntent.class, String.class);
m.setAccessible(true);
m.invoke(sms_smg, pdus.encodedScAddress, pdus.encodedMessage, null, null, phoneNumber);
}
Log.d(TAG, "SMS sent");
} catch (SecurityException e) {
Log.e(TAG, "Exception: Security !");
e.printStackTrace();
}
catch (NoSuchFieldException e) {
Log.e(TAG, "Exception: Field mDispatcher not found !");
e.printStackTrace();
} catch (IllegalArgumentException e) {
Log.e(TAG, "Exception: Illegal Argument !");
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.e(TAG, "Exception: Illegal access !");
e.printStackTrace();
} catch (NoSuchMethodException e) {
Log.e(TAG, "Exception: sendRawPdu() not found !");
e.printStackTrace();
} catch (InvocationTargetException e) {
Log.e(TAG, "Exception: cannot invoke sendRawPdu() !");
e.printStackTrace();
}
}
I found my Answer. More About this you can read in Hush SMS
SmsManager sm = SmsManager.getDefault();
// Get method "sendRawPdu"
byte[] bb = new byte[1];
SmsMessage.SubmitPdu mypdu = SmsMessage.getSubmitPdu(null, pNo, msg, true);
size = (int) mypdu.encodedMessage[2];
size = (size / 2) + (size % 2);
mypdu.encodedMessage[size + 5] = (byte) 0xF0;
Log.d(TAG, dumpHexString(mypdu.encodedMessage, 0, mypdu.encodedMessage.toString().length()));
Method m2 = SmsManager.class.getDeclaredMethod("sendRawPdu", bb.getClass(),bb.getClass(),PendingIntent.class,PendingIntent.class,boolean.class,boolean.class);
Log.d("success", "success getting sendRawPdu");
m2.setAccessible(true);
int length = msg.length();
count = length / 160;
int m = length % 160;
if (m != 0) {
count++;
}
m2.invoke(sm, mypdu.encodedScAddress,mypdu.encodedMessage,sentPI,deliveredPI, Boolean.valueOf(true),Boolean.valueOf(true));
Log.d("success", "success sending message");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Why cant Android open connection with RN-41 Roving network device?

I am just trying to open socket with RN-41 microchip, as far as I know the chip listens for incoming connections all the time, is discoverable, etc.. Why do socket gets always closed directly?
private class Connect extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public Connect(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("EB46DDA9-0D00-4C34-9365-D6AA6C111D1C"));
Log.v("SOCKET SUCCESS", "HAST SOCKET");
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
try {
mmSocket.connect();
Log.v("SOCKET SUCCESS", "VERBUNDEN");
} catch (IOException connectException) {
Log.v("SOCKET SUCCESS", "KEINE VERBINDUNG");
try {
mmSocket.close();
Log.v("SOCKET SUCCESS", "SOCKET CLOSED");
} catch (IOException closeException) {
Log.v("SOCKET SUCCESS", "SOCKET CLOSE FAIL");
}
return;
}
}
I've been googling all day long and got things work. Unfortunately I still dont know why and how it works, but it works perfectly. I changed my Connect class constructor code like this:
public Connect(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 {
// MY_UUID is the app's UUID string, also used by the server code
//ParcelUuid[] ids = device.getUuids();
//UUID deviceID = ids[0].getUuid();
//tmp = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));//deviceID);//UUID.fromString("EB46DDA9-0D00-4C34-9365-D6AA6C111D1C"));
Method m = null;
try {
m = mmDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = (BluetoothSocket)m.invoke(mmDevice, Integer.valueOf(1));
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("SOCKET SUCCESS", "HAST SOCKET");
//} catch (IOException e) { }
mmSocket = tmp;
}
Source:
Android Bluetooth SPP with Galaxy S3
P.s. If somebody would have a bit time to explain code above, I would appreciate it a lot. Thank you.

data not sent using bluetooth socket (android)

I am trying to send a file using Android bluetooth sockets. I am getting the pairing requests but unfortunately the data is not being transferred
my Server side and client side is as follows:
Server: (for my application server is receiving the data)
public void run() {
super.run();
BluetoothAdapter mBtadapter = BluetoothAdapter.getDefaultAdapter();
Log.i("bluetooth Adapter", "got adapter "+ mBtadapter.getAddress());
try {
Ssocket = mBtadapter.listenUsingRfcommWithServiceRecord("CardXchange", uuid);
Log.i("Socket", "Socket Acquired "+ Ssocket.toString());
} catch (IOException e) {
e.printStackTrace();
}
while(true){
if(read_flag()==1){
try {
Toast.makeText(c, "flag is eventually 1", Toast.LENGTH_LONG).show();
Ssocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
try {
client_socket = Ssocket.accept();
if(client_socket!=null){
//this function is used to handle the connection when sockets get connected
manageConnection1(client_socket);
Ssocket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("breaked ", "oh god!! out of the loop ");
}
//implementation of the function
private void manageConnection1(BluetoothSocket client_socket2) {
// TODO Auto-generated method stub
int bytes;
Log.i("serevr chya manage connection madhe gela", "in servers manage connection ");
File file = new File("/sdcard/myfolder/received.Xcard");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
InputStream is = client_socket2.getInputStream();
while((bytes = is.read(buffer, 0, 1024))>0){
fos.write(buffer, 0, 1024);
}
is.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
client_socket2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and the client side (the sending side is like this):
public void run(){
try {
Method m = send_dev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
Csocket = (BluetoothSocket) m.invoke(send_dev, 1);
Csocket.connect();
manageSendConnection(Csocket);
}catch(Exception e){
e.printStackTrace();
}
}
//function to handle after connection is established.
private void manageSendConnection(BluetoothSocket csocket) {
// TODO Auto-generated method stub
File f = new File("/sdcard/myfolder/card3.Xcard");
byte[] buffer = new byte[(int)f.length()];
try {
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(buffer, 0, (int)f.length());
OutputStream os = csocket.getOutputStream();
os.write(buffer);
os.close();
fis.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
csocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am getting the pairing request but the data is not being sent.
can anyone please help me to find the problem and give a hint on solution??

Android How to read response of TCP client on port 502

I am developing an application to send a request to port 502 and want to read the response from the same port.
This is what i tried so far
public class Autoamtion extends Activity {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.v("on create", "on create");
final ToggleButton fanOn = (ToggleButton) findViewById(R.id.toggleButton1);
fanOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (fanOn.isChecked()) {
Toast.makeText(Autoamtion.this, "Fan is On",
Toast.LENGTH_SHORT).show();
Log.v("on create", "on create");
try {
echoSocket = new Socket("192.168.1.19", 502);
out = new PrintWriter(echoSocket.getOutputStream(),
true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to:192.168.1.19");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stdIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
echoSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
Toast.makeText(Autoamtion.this, "Fan is Off",
Toast.LENGTH_SHORT).show();
}
});
}
}
i just installed one simulator which opens the port 502. i confirmed that port which gets open after running this simulator.
i just established the connection with 502 port. i am not getting any response from there.
Please guide me through this so i can make this working. Any advice and help would be appreciated .
Thanks
You should post stackTrace as well, to check what's failling.
At least one thing is not consistent in your information, your refer in the text port 503 and in your code you are using echoSocket = new Socket("192.168.1.19", 502); connecting to port 502.

Categories

Resources