Bluetooth does not see a device - android

I create app which work with bluetooth and almost everything is ok but one this is not cool. So after I connect device do some staff save everything them disconnect it, my app stops seeing this device is no more on my list, but after 5-10 minutes device back on the list. What can be the issue?
public class MainActivity extends AppCompatActivity {
static final int SEND_TIMES = 1;
static final int SEND_DATE = 2;
List<BluetoothDevice> devices;
Spinner devicesSpinner = null;
BluetoothAdapter bluetoothAdapter = null;
BluetoothSocket clientSocket = null;
OutputStream outputData = null;
InputStream inputData = null;
List<String> devicesNames = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) {
Intent enableRequest = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableRequest);
}
findDevices();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(deviceFoundReceiver, filter);
registerReceiver(bondStateChangeReceiver, filter);
devices = new ArrayList();
devicesSpinner = findViewById(R.id.devices_list);
devicesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
if(devices.get(i) == null)
return;
BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(devices.get(i).getAddress());
Method m = remoteDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
clientSocket = (BluetoothSocket) m.invoke(remoteDevice, 1);
outputData = clientSocket.getOutputStream();
inputData = clientSocket.getInputStream();
} catch (Exception e){
Log.i("REMOTE_DEVICE", "No such a method", e);
}
}
#Override
public void onNothingSelected (AdapterView<?> adapterView){
}
});
if(clientSocket != null)
Toast.makeText(this, "" + clientSocket.isConnected(), Toast.LENGTH_LONG);
}
public void connectDevice(View view) throws IOException {
if (isSocketConnected()) return;
bluetoothAdapter.cancelDiscovery();
if(!clientSocket.isConnected()){
try {
clientSocket.connect();
} catch (Exception e){
Toast.makeText(this, "Can not connect to this device try later!", Toast.LENGTH_LONG).show();
return;
}
TextView textView = (TextView) findViewById(R.id.boundedDevice);
textView.setText(clientSocket.getRemoteDevice().getName());
}
}
public void disconnectDevice(View view) throws IOException {
if(clientSocket.isConnected()){
clientSocket.close();
TextView textView = (TextView) findViewById(R.id.boundedDevice);
textView.setText("Device not connected");
}
}
}
That is my code which I am using for connection, what is wrong?
What I want to have is I would like to have my device straight away on my list after disconnection, to not waiting those 5-10 mins to let my app find it again.

This is client-side code and you need server-side code.So you need two device and one device must be a server another device must be a client.If you want to search available device you work in server side.First of all you must look at android developer bluetooth chat project in the official site.Then find out server-side code.
https://developer.android.com/samples/BluetoothChat/project.html

Related

How to send hard coded string from Android APP when button is pressed to a UDP listener in Node-Red?

OVERVIEW
I'm using Android Studio to make an app that on a button press sends a string to a UDP listener in Node-Red running on my laptop, Node-Red filters anything that comes in and function nodes do their thing. This app will work inside a LAN not over the internet.
So far I have made a new project with an empty activity and my activity_main.xml has the button. There is no need for the user to input a string/text so the button press code will have the "string" and Node-Red listener IP and port hard coded.
There is also no need to receive a reply from the laptop/node-red side so the button press should be a fire and forget hard coded message hence UDP and not a TCP socket.
QUESTION
What code is required for the MainActivity to send the string when the button is pressed to the UDP listener in Node-Red?
I have spent a long time scouring the internet for answers and tried many code examples however they have not worked. A lot of the research I've seen is people with UDP receive problems, however I cannot understand their code for sending UDP.
I finally worked it out with a ridiculous amount of trial and error... please see the code below if anyone else ever gets the same problem:
//On button press the message is sent via UDP
findViewById(R.id.btSendMessage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int txnumber = Integer.parseInt(((TextView) findViewById(R.id.transmitnumber)).getText().toString());
String data = ((TextView) findViewById(R.id.texttosend)).getText().toString();
int port = Integer.valueOf(((TextView) findViewById(R.id.serverport)).getText().toString());
String address = ((TextView) findViewById(R.id.serverip)).getText().toString();
SendData(txnumber, data, port, address);
}
});
private DatagramSocket UDPSocket;
private InetAddress address;
private int port;
public void Theaddress(InetAddress address) {
try {
this.UDPSocket = new DatagramSocket();
this.address = address;
} catch (SocketException e) {
e.printStackTrace();
}
}
public void SendInstruction(final byte[] data, final int port) {
new Thread() {
#Override
public void run() {
try {
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
UDPSocket.send(packet);
DatagramPacket packetreponse = null;
UDPSocket.receive(packetreponse);
DisplayData(packetreponse);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void SendData(final int nbRepet, final String Sdata , final int port, final String address) {
new Thread() {
#Override
public void run() {
try {
Theaddress(InetAddress.getByName(address));
for (int i = 0; i < nbRepet; i++) {
byte[] data = Sdata.getBytes();
SendInstruction(data,port);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void ReceiveData(final int portNum) {
new Thread() {
#Override
public void run() {
try {
final int tally = 1024;
final byte[] buffer = new byte[tally];
DatagramSocket socketReceive = new DatagramSocket(portNum);
while (true) {
DatagramPacket data = new DatagramPacket(buffer, buffer.length);
socketReceive.receive(data);
DisplayData(data);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void DisplayData(DatagramPacket data) {
System.out.println(data);
}

Communication on 2 ports between 2 Android devices using WiFi Direct

I am creating an application that will monitor movements in a particular Android device (client) and report such instances to another Android device (server). Also, under specific conditions, the client will take a picture and transmit the image to the server.
I am using WiFi direct to setup the connection between the two devices. After that I am using socket connections as explained in the WiFi Direct Demo. I am using port 8988 to send the motion sensor events and I am using port 8987 to send the images capture.
On the server side, I am using two different instances of the same Async Task with serversocket connecting to different ports to listen for the incoming messages. Everything works fine as long as only the motion sensor events are being sent across. The first image capture is also being sent/received correctly. However, after that the server doesn't receive any additional messages. I tried having two different Async Task classes to avoid having two instances of the same class but that didn't work as well. I also tried having one as an Async Task and another as an Intent Service but even that doesn't work.
This is IntentService I am using to send the messages across to the server.
public class MessageSender extends IntentService {
public static final String EXTRAS_TIMEOUT = "timeout";
public static final String EXTRAS_ADDRESS = "go_host";
public static final String EXTRAS_PORT = "go_port";
public static final String EXTRAS_DATA = "data";
private Handler handler;
public MessageSender(String name) {
super(name);
}
public MessageSender() {
super("MessageTransferService");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler = new Handler();
return super.onStartCommand(intent, flags, startId);
}
#Override
protected void onHandleIntent(Intent intent) {
String host = intent.getExtras().getString(EXTRAS_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_PORT);
byte[] data = intent.getExtras().getByteArray(EXTRAS_DATA);
int timeout = intent.getExtras().getInt(EXTRAS_TIMEOUT);
try {
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), timeout);
OutputStream stream = socket.getOutputStream();
stream.write(data);
} catch (final IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Exception has occurred: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
/*handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Socket Connection closed now..",
Toast.LENGTH_SHORT).show();
}
});*/
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
This is Async Task on the server that starts listeners on two ports (8987 and 8988) to receiver the information of motion sensor events and images.
public class MessageReceiver extends AsyncTask<Void, Void, String> {
private Context context;
private int port;
private Bitmap mBitmap;
public MessageReceiver(Context context, int port) {
this.context = context;
this.port = port;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(port);
Socket client = serverSocket.accept();
InputStream inputstream = client.getInputStream();
String returnString = "";
if (port == MainActivity.PORT_SENSOR_COMM) {
// do something
} else if (port == MainActivity.PORT_IMAGE_COMM) {
//do something
}
serverSocket.close();
return returnString;
} catch (Exception e) {
return "Exception Occurred:" + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
boolean startNewTask = true;
if (port == MainActivity.PORT_SENSOR_COMM) {
//do something
} else if (port == MainActivity.PORT_IMAGE_COMM) {
//do something
}
//doing this to start listening for new messages again
new MessageReceiver(context, port).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
protected void onPreExecute() {
}
}
I am now wondering whether Android WiFiDirect allows parallel communication between two devices on different ports. Searched the docs but could'nt find much help. What I am doing wrong? What is the correct method to accomplish what I am trying to do? Any help would be greatly appreciated. Thanks for looking.

How can I connect two Android device by socket without server

I am trying to develop an android application that can exchange data on peer to peer connection with other devices without server. So please suggest how can I do this. Thank you in advance.
This is a complete code for chat by SocketProgramming without server.
In my Application, first you are a client and you search for a server. When you do not find any server, you become a server and wait for a client.
public class MainActivity extends ActionBarActivity {
private Handler handler = new Handler();
private TextView text;
private EditText input;
private Button send;
private Socket socket;
private DataOutputStream outputStream;
private BufferedReader inputStream;
private String DeviceName = "Device";
private boolean searchNetwork() {
log("Connecting");
String range = "192.168.56.";
for (int i = 1; i <= 255; i++) {
String ip = range + i;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, 9000), 50);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DeviceName += "1";
Log.i("Server", DeviceName);
log("Connected");
return true;
} catch (Exception e) {
}
}
return false;
}
private void runNewChatServer() {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(9000);
log("Waiting for client...");
socket = serverSocket.accept();
DeviceName += "2";
log("a new client Connected");
} catch (IOException e) {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
input = (EditText) findViewById(R.id.input);
send = (Button) findViewById(R.id.send);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
if (!searchNetwork()) {
runNewChatServer();
}
outputStream = new DataOutputStream(
socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
while (true) {
String Message = inputStream.readLine();
if (Message != null) {
log(Message);
}
}
} catch (IOException e) {
log("Error: IO Exception");
e.printStackTrace();
}
}
});
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (outputStream == null) {
return;
}
try {
String Message = input.getText().toString() + "\n";
outputStream.write(Message.getBytes());
log2(input.getText().toString());
} catch (IOException e) {
e.printStackTrace();
}
input.setText("");
}
});
thread.start();
}
private void log(final String message) {
handler.post(new Runnable() {
String DeviceName2="";
#Override
public void run() {
if (DeviceName.equals("Device1")) {
DeviceName2 = "Device2";
}else if(DeviceName.equals("Device2")) {
DeviceName2 = "Device1";
}else{
DeviceName2 = "UnknowDevice";
}
text.setText(text.getText() + "\n" + DeviceName2 + " :"
+ message);
}
});
}
private void log2(final String message) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText(text.getText() + "\n" + "you" + " :"
+ message);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.exit(0);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Your design has a big problem : ...
If there is no central server some android devices should act as client and others as server but this will not work in some situations:
When the mobile telephony provider assigns private and non-public IP
When the device is connected to a Wi-Fi network but no NAT rule is defined on the router.
In both cases the problem is that the listening port of the device that must act as server is unreachable.
Java provides ServerSocket and Socket to communicate b/w devices. One of the device you can make as server and other device you can make as client and communicate b/w 'em without introducing server hosted on some machine.
The Other and better option is Using Wi-Fi Peer-to-Peer. WifiP2pManager help you to achieve your purpose.Here is an example.
If you're looking for such P2P over a local network, there are two parts to it:
Discovering peers
Communicating with peers
Among Android APIs, you can either use Network Service Discovery APIs for this or Wifi P2P Service Discovery APIs.
There's a wrapper library which which uses these internally and has comparatively better documentation - Salut, which can also be used.
I also created a library for P2P - Near, which uses sockets directly. The problem I was facing with Android APIs was that discovery wasn't happening with certainty every time and the underlying issue was unknown.
If you're looking for P2P across the internet, socket IO is a prevalent solution. Even Near should be able to facilitate the transfers if you provide the IP addresses and they're not behind NAT firewalls.

Android want to send bluetooth pair request to another devices

i want to search and listing bluetooth devices in android, my program now able to list all the active devices but not able to send pairing request to the other devices .I want to implement this onItemClick of list element.And also if bluetooth is not enabled of my device then show a permission to active device,if i go for yes then ok,but if i go for no then permission show again until i press yes..how can i do this?plz help with code..here is my code..
public class Main extends Activity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter;
private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();
private ArrayList<String> mylist= new ArrayList<String>();
private ListView lv;
private Button btn;
public Parcelable[] uuidExtra;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void search(View view)
{
//Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_UUID);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(ActionFoundReceiver, filter); // Don't forget to unregister during onDestroy
// Getting the Bluetooth adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
Toast.makeText(getApplicationContext(),"\nAdapter: " + btAdapter,5000).show();
CheckBTState();
}
private void setDeviceList(ArrayList<String> list) {
lv = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
}
/* This routine is called when an activity completes.*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
CheckBTState();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (btAdapter != null) {
btAdapter.cancelDiscovery();
}
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// If it isn't request to turn it on
// List paired devices
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
Toast.makeText(getApplicationContext(),"\nBluetooth NOT supported. Aborting.",5000).show();
return;
} else {
if (btAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(),"\nBluetooth is enabled...",5000).show();
// Starting the device discovery
btAdapter.startDiscovery();
} else if (!btAdapter.isEnabled()){
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
/* else{
Intent intent = new Intent(btAdapter.ACTION_STATE_CHANGED);
startActivityForResult(intent, RESULT_CANCELED);
}*/
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device,5000).show();
mylist.add(device.getName());
setDeviceList(mylist);
} else {
if(BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
for (int i=0; i<uuidExtra.length; i++) {
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString(),5000).show();
}
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Started...",5000).show();
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Finished",5000).show();
Iterator<BluetoothDevice> itr = btDeviceList.iterator();
while (itr.hasNext()) {
// Get Services for paired devices
BluetoothDevice device = itr.next();
Toast.makeText(getApplicationContext(),"\nGetting Services for " + device.getName() + ", " + device,5000).show();
if(!device.fetchUuidsWithSdp()) {
Toast.makeText(getApplicationContext(),"\nSDP Failed for " + device.getName(),5000).show();
}
}
}
}
}
}
}
};
}
It's too late but here is code -> You need to use background thread to connect with bluetooth device as a client. and UUID is Universal Uniquely identification you can use online UUID generator. for secure connections and then get socket with device and connect with it;
ConnectWithDevice(context : ConnectWithBluetooth, device : BluetoothDevice) : Thread(){
private val mContext : ConnectWithBluetooth = context
private val mmSocket : BluetoothSocket
private val mmDevice : BluetoothDevice
// Default UUID
private val mmDefaultUUID = UUID.fromString("78c374fd-f84d-4a9e-aa5b-9b0b6292952e")
init {
var temp : BluetoothSocket? = null
mmDevice = device
try {
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)
}catch (en : NullPointerException){
en.printStackTrace()
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDefaultUUID)
}catch (e : IOException){
e.printStackTrace()
Log.e("TAG","Socket's create() method failed",e)
}
mmSocket = temp!!
Log.i("TAG","Got the Socket")
}
override fun run() {
// Cancel discovery because it otherwise slows down the connection.
if(mContext.bluetoothAdapter != null){
mContext.bluetoothAdapter!!.cancelDiscovery()
}
try{
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
Log.i("TAG","Connecting...")
mmSocket.connect()
Log.i("TAG","Bluetooth Successfully Connected")
}catch (connectException : IOException){
// Unable to connect; close the socket and return.
try{
mmSocket.close()
}catch (closeException : IOException){
Log.e("TAG","Could not close the client socket",closeException)
}
return
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
Log.i("TAG","Device is Connected")
//manageMyConnectedSocket(mmSocket)
}
// Closes the client socket and causes the thread to finish.
// Call this method from the main activity to shut down the connection.
fun cancel(){
try {
mmSocket.close()
} catch (e: IOException) {
Log.e(ContentValues.TAG, "Could not close the client socket", e)
}
}
}

unable to connect to bluetooth socket on android

I am trying to sent message from android client to Mac OS X over bluetooth.
I am using bluecove 2.0.1 Java bluetooth library on Mac OS X Snow Leopard.
Code for Server:
public class EchoServer2 {
private static final String UUID_STRING = "00001101-0000-1000-8000-00805F9B34FB"; // 32 hex digits
private static final String SERVICE_NAME = "echoserver";
private LocalDevice mLocalDevice;
public EchoServer2() {
try {
mLocalDevice = LocalDevice.getLocalDevice();
} catch(IOException e) {
System.err.print("Error connection to bluetooth");
}
}
public void start() throws IOException {
StreamConnectionNotifier connectionNotifier =
(StreamConnectionNotifier) Connector.open(
"btspp://localhost:" + UUID_STRING +
";name=" + SERVICE_NAME + ";authenticate=false");
System.out.println("Bluetooth Address: " + mLocalDevice.getBluetoothAddress());
System.out.println("Waiting for a connection...");
StreamConnection streamConnection = connectionNotifier.acceptAndOpen();
System.out.println("Found a new device.");
RemoteDevice device = RemoteDevice.getRemoteDevice(streamConnection);
System.out.println("New Device connected: " + device.getFriendlyName(false).toString());
DataInputStream is = streamConnection.openDataInputStream();
byte[] bytes = new byte[1024];
int r;
while((r = is.read(bytes)) > 0) {
System.out.println(new String(bytes, 0, r));
}
}
}
Code for Android client:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
EditText editText;
TextView textView;
String send_msg;
String rcv_msg;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // 32 hex digits
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
editText = (EditText) findViewById(R.id.edit_msg);
textView = (TextView) findViewById(R.id.rcv_msg);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(adapter == null) {
textView.append("Bluetooth NOT Supported!");
return;
}
// Request user to turn ON Bluetooth
if(!adapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, RESULT_OK);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onClick(View view) {
Log.d(TAG, "onClick");
new SendMessageToServer().execute(send_msg);
}
private class SendMessageToServer extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... msg) {
Log.d(TAG, "doInBackground");
BluetoothSocket clientSocket = null;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable();
// Client knows the server MAC address
BluetoothDevice mmDevice = mBluetoothAdapter.getRemoteDevice("00:25:00:C3:1C:FE");
Log.d(TAG, "got hold of remote device");
Log.d(TAG, "remote device: " + mmDevice.getName().toString());
try {
// UUID string same used by server
clientSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
Log.d(TAG, "bluetooth socket created");
mBluetoothAdapter.cancelDiscovery(); // Cancel, discovery slows connection
clientSocket.connect();
Log.d(TAG, "connected to server");
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
out.writeUTF(msg[0]); // Send message to server
Log.d(TAG, "Message Successfully sent to server");
return in.readUTF(); // Read response from server
} catch (Exception e) {
Log.d(TAG, "Error creating bluetooth socket");
Log.d(TAG, e.getMessage());
return "";
}
}
#Override
protected void onPostExecute(String result) {
Log.d(TAG, "onPostExecute");
rcv_msg = result;
textView.setText(rcv_msg);
}
}
}
I am not able to connect to server even though the UUID are same both for client and server.
Android throws an exception: Service Discovery failed.
However I am able to print the name of remote device (client) on the server. Hence acceptAndOpen() is unable to accept the socket connection.
Please help me in understanding as to why I am unable to clientSocket.connect(); on android ?
Im gonna take a guess and say it has something to do with the UUID numbers you used. They depend solely on the type of device you use. So make sure you look those up and that they are correct for the android device. When i was doing android this stumped me for a long time.
UUID is not something you set.
Here is a link
How can I get the UUID of my Android phone in an application?
Or this
Android - Get Bluetooth UUID for this device
If that is not it.
Did discovery fail on both ends? can you see the device on either end? Which side can you print the name?
You might want to take a look at google's bluetooth sample program. And use that to get you started.

Categories

Resources