Connect to a bluetooth device, exception: Service discovery failed - android

Iam trying to connect my android device with a bluetooth compatible device. I know the mac-address of this device, as you can see in my code below. I also made several Toasts just to verify the steps in the code. It seems that I manage to create tmp = device.createRfcommSocketToServiceRecord(MY_UUID); I assume this because the Toast raises a message saying some bluetooth object address, in this line of code:
String test = tmp.toString();
Toast.makeText(getApplicationContext(), "The bluetooth socket: " +test, Toast.LENGTH_LONG).show();
But the code failes semantically when I do a tmp.connect(); I am working on API level 15, android 4.0
This i my piece of code
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleConnectAndroidActivity extends Activity {
final static String toast = "IAM HERE";
final static String TAG ="SimpleConnect";
UUID MY_UUID;
BluetoothDevice bd;
BluetoothAdapter ba;
Button connectButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
ba = BluetoothAdapter.getDefaultAdapter();
connectButton = (Button)findViewById(R.id.button1);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
boolean b = ba.checkBluetoothAddress("00:1B:DC:0F:EC:7E");
BluetoothSocket tmp = null;
//If valid bluetoothAddress
if(b) {
final BluetoothDevice device = ba.getRemoteDevice("00:1B:DC:0F:EC:7E"); //Getting the Verifier Bluetooth
//Trying to create a RFCOMM socket to the device
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
try {
tmp.connect();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "No connection was made! Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
//Print out the sockets name
String test = tmp.toString();
Toast.makeText(getApplicationContext(), "The bluetooth socket: " +test, Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "FALSE, No bluetooth device with this address", Toast.LENGTH_LONG).show();
}
}
});
}
}
I am aware of that this should be done in a separate thread, and yes, I read the Bluetooth Chat example provided by Google.
Can someone help me out?
EDIT
This is the only thing I got from LogCat:
07-06 10:10:22.085: V/BluetoothSocket.cpp(14019): ...fd 63 created (RFCOMM, lm = 26)
EDIT 2
Ok, now got a new error, but its a better error. When i press the connect button, the phone asks for the pin code for pair the devices, but its already paired! After I paired it for the second time, the error says: Connection refused and another exception says, timeout.

you can use this code:Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mySocket = (BluetoothSocket) m.invoke(device, 1);

Related

can't connect my android app to the net, only through my home wifi it work fine

I am building an app in Android Studio, and using a sql server, the app works great on my home WIFI network. I manage to connect to the server and do enter / read / update the data.
But the problem is that outside the home network the app does not work, why?
(its work fine in the home wifi, but when i'm going out of range of my wifi, its not working\connecting)
The SQL SERVER is on my home computer (meaning the same IP)
how to make it work on any android phone app and Everywhere ?
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
String ip = "192.168.1.15";
String classes = "net.sourceforge.jtds.jdbc.Driver";
String db = "myDB";
String un = "mtun";
String password = "mypw";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL;
try {
Class.forName(classes);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"+db+";user=" + un+ ";password=" + password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERROR-1", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERROR-2", e.getMessage());
} catch (Exception e) {
Log.e("ERROR-3", e.getMessage());
}
return conn;
}
}```

Readline method in Android TCP Server not reading the message sent from my Python Client

I am trying to send a message named "ringdoor" from the python client to the android TCP server. However, the readline method in the Server code is not reading the message.
please note:
1) that I am using "sendall" to send the message from the python client
2)I am using the bufferedReader class and readline method to read messages from the client.
3) The codes for the client and the server are below.
Server code in Java
package com.example.mmz_10.test7;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// startService(new Intent(getBaseContext(), Server.class));
Thread ServerThread= new Thread(new MyServerThread());
// starting the thread to do work in the background
ServerThread.start();
// Log.d("Server.java", "Starting server...");
}
// https://developer.android.com/reference/java/lang/Thread.html
public class MyServerThread implements Runnable {
Socket socket;
ServerSocket serverSocket;
InputStreamReader isr;
BufferedReader br;
String message;
#Override
public void run (){
try
{
int port = 8080;
serverSocket = new ServerSocket(port);
// Now the server just started and is listening to port 4457
System.out.println ("the server just started and is listening to port 4457");
//To make Server run forever, we use "while(true)" loop as shown below
while(true)
{
//Reading the message from the client (raspberry pi 3)
// Log.d("Server.java", "Listening on port " + port);
socket = serverSocket.accept();
System.out.println ("the server just accepted the connection from the client");
System.out.println ("preparing to read the message" );
isr = new InputStreamReader(socket.getInputStream()); // side note :InputStreamReader is equivalent to DataInputStream
br = new BufferedReader(isr);
message = br.readLine(); // message received from the client
System.out.println ("preparing to print the message" );
if (message!=null){
System.out.println ("the messagee is not null");
}else {
System.out.println ("the message is null");
}
// System.out.println(br);
if (message.equals("ring")){
// starting an activity from the service
Intent intent = new Intent(MainActivity.this, RingCall.class); // The " Server.this" or in general "ClassName.this" is used for nested classes when an inner class need to use the outer class
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} // end of if
} // end of the "while(true)" loop
} // end of the "try block"
catch (IOException e)
{
e.printStackTrace();
}
//finally
//{
// try
//{
// socket.close();
//}
//catch(Exception e){}
//}
}// end of the "run" method
} // end of "MyServerThread" class
}
**Client in python**
Import socket
import sys
try:
s=socket.scoket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error:
print ('Failed to create socket')
sysc.exit();
print ('Socket Created')
port=8080
remote_ip="192.168.0.100"
s.connect((remote_ip,port))
message="ring"
try:
s.sendall(b'ringdoor')
except socket.error
print ('send failed)
sys.exit()
print ('message sent successfully to the server')

Cannot start VPN using Toyvpn

I'll try to be as descriptive as possible
I'm new to android and i'm making an android application
In that application i'd like to be able to see the address of the HTTP requests going OUT from the mobile (On what website they are heading).
So i've looked around and i found out that to do that , I need to use a VPN and android 4.0+ has a VPNService supplied from google implemented using ToyVPNService
So i got this service and started changing in it so i can use it without the need of using a server
I'd like to work the VPN as follows:
1-Capture the HTTP requests
2-Read their destination
3-Resend them back to their way
So i took the VPNService and i started modifying it so that i don't need an actual server
Here's the code i'm using
package com.example.testingservice;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.VpnService;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Enumeration;
public class SO1 extends VpnService implements Handler.Callback, Runnable {
private static final String TAG = "ToyVpnService";
private Handler mHandler;
private Thread mThread;
private ParcelFileDescriptor mInterface;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Stop the previous session by interrupting the thread.
if (mThread != null) {
mThread.interrupt();
}
// Start a new session by creating a new thread.
mThread = new Thread(this, "ToyVpnThread");
mThread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
if (mThread != null) {
mThread.interrupt();
}
}
#Override
public boolean handleMessage(Message message) {
if (message != null) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public synchronized void run() {
Log.i(TAG,"running vpnService");
try {
runVpnConnection();
} catch (Exception e) {
e.printStackTrace();
//Log.e(TAG, "Got " + e.toString());
} finally {
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = null;
mHandler.sendEmptyMessage(R.string.disconnected);
Log.i(TAG, "Exiting");
}
}
private boolean runVpnConnection() throws Exception {
configure();
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
Log.i(TAG,"************new packet");
System.exit(-1);
while (packet.hasRemaining()) {
Log.i(TAG,""+packet.get());
//System.out.print((char) packet.get());
}
packet.limit(length);
// tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
}
Thread.sleep(50);
}
}
public String getLocalIpAddress()
{
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
Log.i(TAG,"****** INET ADDRESS ******");
Log.i(TAG,"address: "+inetAddress.getHostAddress());
Log.i(TAG,"hostname: "+inetAddress.getHostName());
Log.i(TAG,"address.toString(): "+inetAddress.getHostAddress().toString());
if (!inetAddress.isLoopbackAddress()) {
//IPAddresses.setText(inetAddress.getHostAddress().toString());
Log.i(TAG,"IS NOT LOOPBACK ADDRESS: "+inetAddress.getHostAddress().toString());
return inetAddress.getHostAddress().toString();
} else{
Log.i(TAG,"It is a loopback address");
}
}
}
} catch (SocketException ex) {
String LOG_TAG = null;
Log.e(LOG_TAG, ex.toString());
}
return null;
}
private void configure() throws Exception {
// If the old interface has exactly the same parameters, use it!
if (mInterface != null) {
Log.i(TAG, "Using the previous interface");
return;
}
// Configure a builder while parsing the parameters.
Builder builder = new Builder();
String SS=getLocalIpAddress();
builder.setMtu(1500);
// builder.addAddress("10.0.0.2", 24);
builder.addAddress(SS, 24);
// builder.addAddress(SS,24);
builder.addRoute("0.0.0.0",0);
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = builder.establish();
}}
The problem is this line
mInterface = builder.setSession("GITVPN").setConfigureIntent(mConfigureIntent).establish();
the Establish returns NULL and i can't seem to get it working
I'm thinking there is a problem with the addresses
I'd like to work it that there's no server , and there would be a tunnel that reads the packets
I've seen some other post that said i should make the addresses to 10.0.0.2 instead of external ips ( 192.168.x.x) and i should add route (0.0.0.0,0)
However the descriptor file keeps returning null and i can't seem to fix it
Any help will be appreciated , and sorry if this sounded that it was repeated but i'm super stuck and you guys are my only hope
You can't run the VpnService and establish a VPN connection without having a server that you communicate with and forwards the traffic to the internet.
Check the IP address you assigned to the interface, it should not be the same as other adapters.
What the builder operated on is a TUN device, which is created for VPN service.
So, IP address of the TUN should be proper set.
Make the address conflict with others is not a good idea.
Also, Step 3 you mentioned is not quite easy as Android not support raw socket.
just to revive an old thread...
VpnService requires a users interaction to start and won't work without it
the ToyVpnClient puts a button on the screen that the user has to click and once that's done, the Builder method will return the interface
so, steps to make it work are;
1. build a button on your app
2. onclick of that button, call VpnService.prepare(this); (this = your app context)
3. Builder.establish() will now return a VPN interface

Android UDP socket unable to send data

I'm newbie in Android programing, and I wanted to write a piece of code which simply send a string on 127.0.0.1 and I will be able to watch it on netcat but the problem is when I try it on my android project nothing happen, so I've tried in a usual java project and everything work well.
So after a lot of research I've find... nothing
My android code :
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.net.*;
import java.io.*;
public class MainActivity extends Activity {
public static final int MON_PORT = 5001;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bouton2 = (Button)findViewById(R.id.envoi);
bouton2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
int port=MON_PORT;
InetAddress adresse = InetAddress.getByName("localhost");
DatagramSocket socket;
String leMessage = "test";
int longueur = leMessage.length();
byte[] message= new byte [longueur];
message = leMessage.getBytes();
socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(message,longueur,adresse,port);
socket.send(packet);
System.out.println("test d'execution");
socket.close();
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SocketException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
And I've checked my AndroidManifest.xml and the permission :
<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> </uses-permission>
are not between the applications tag
I use an AVD based on Android API 7 but I've tried on an another AVD with API 16 but results are the same, could someone help me to find what's wrong ?
Thanks
The actual problem is that your PC has no access to the UDP packet you are sending because that packet is being sent on a different IP address that device "emulator" uses through the Loopback mechanism.
Here is the thing. You can safely assume that the Android emulator is a remote machine that is remotely connected to your PC through an IP network, it has its own IP address and can communicate with your PC. You can't just use loopback IP to communicate with your PC over IP. Please use 10.0.2.2 instead as specified in this documentation page Emulator.
Using that IP you will be able to see the packets in netcat.

Android bluetooth exception

Ok, I will try one more time.
I have a device sdptool in ubuntu the following is stated from my device:
# sdptool browse C0:1B:DC:1F:E2:F1
Browsing C0:1B:DC:1F:E2:F1 ...
Service Name: OBEX Object Push
Service RecHandle: 0x10000
Service Class ID List:
"OBEX Object Push" (0x1105)
Protocol Descriptor List:
"L2CAP" (0x0100)
"RFCOMM" (0x0003)
Channel: 9
"OBEX" (0x0008)
Profile Descriptor List:
"OBEX Object Push" (0x1105)
Version: 0x0100
As you can se the device does support the RFCOMM protocol, and OBEX for file transfer. I have a simple code for my android app which tries to connect to this device over a insecure RFCOMM channel, just for no user interaction. I want to connect to this device, so Iam using the device mac-address for connection, and the socket is ready, logcat says so.
But I only get the error:
Connection refused
Have in mind that the mac-address in the java code is different from the following listed above.
So here is my code:
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleConnectAndroidActivity extends Activity {
final static String toast = "IAM HERE";
final static String TAG ="SimpleConnect";
UUID MY_UUID;
BluetoothDevice bd;
BluetoothAdapter ba;
Button connectButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//MY_UUID = new UUID(0x0100 , 0x1000);
// MY_UUID = UUID.fromString("8e1f0cf7-508f-4875-b62c-fbb67fd34812");
connectButton = (Button)findViewById(R.id.button1);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BluetoothSocket tmp = null;
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:1B:DC:0F:EC:7E");
Method m = null;
try {
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
} catch (IllegalAccessException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (InvocationTargetException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
try {
tmp.connect();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
try {
tmp.close();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(), "Socket closed!" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
boolean con = tmp.isConnected();
if(con)
Toast.makeText(getApplicationContext(), "Connection was made!", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Connection was not made!", Toast.LENGTH_LONG).show();
}
});
}
}
I've read several places that it should work by un-pairing and pair again, but this doesn't solve my problem.
Well, your question is over a month old, but in case you're still looking for the answer, here's one:
sdptool indicates that your RFCOMM channel is 9, but in your code you have:
tmp = (BluetoothSocket) m.invoke(device, 1);
Instead of 1 as your last argument, try 9 (if that doesn't work, try other integers, like 2 through 15).
You may also want to check out this answer.
There seem to be many variations of this question on Stack, but not a lot of understanding of the "standard" recommended code (i.e., the bluetooth chat sample modified with the lines that define and invoke "Method m")--I know because I'm one of those people who struggled with this. I was trying to connect my phone to my MacBook, and got the "connection refused" message until I realized that I needed to use 5 in the line of code above.

Categories

Resources