so i'm trying to do something a little unusual, it's just for fun. I have a game i created using libgdx, it consists of a ship that can shoot. What i want to do is to use some external push buttons to move it. The push buttons send signals to arduino, which in turn sends them to an HC-05 bluetooth module. however i'm very doubtful about the android side of things. What i did basically was the following:
Because i'm working on libgdx i created an interface called BluetoothDude, with three methods setBluetooth() (which will set the bluetooth for the particular platform),String whatIsTheMessage() (which will tell you what's been sent to the phone), and boolean isActive(), to know if the bluetooth is active of course.
The MainGame will receive a BluetoothDude so that particular classes like Ship have access to the Message and are able to react to it.
Then i did the particular implementation of Bluetooth for android, in the setBluetooth() i followed this guide very closely: https://developer.android.com/guide/topics/connectivity/bluetooth.html
i'm sure it is connecting properly, because when it creates the socket it can print "connection success with HC-05" (it will only print that if the method which creates the sockets, which i called BTConnect() returns true).
The problem seems to be in reading the data, the code i'm using is
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private Handler handler;
public ConnectedThread(BluetoothSocket socket,Handler mHandler) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
handler = mHandler;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
i made an object of this class in setBluetooth like this
if (device != null) {
if (BTconnect()) {
isActive = true;
connectedThread = new ConnectedThread(socket,handler);
System.out.println("connection success with" + device.getName() + " message: " + message );
}
i have a lot of doubts
first what is the target here, the mHandler was created in BluetoothDude, so is that the target?, second i'm quite sure the thread isn't even running because if i put a line like System.out.println("run") inside run() it doesn't show me the line like a trillion times in the logcat when the app is executed. What is wrong with it, i hope you can help me, i'm not very experienced at all of this, and it's driving me crazy.
I cannot see if this is the case from your code but if you are calling platform specific methods, that should be done in the platform specific project subproject.
For more information on how to do that you can check out this page :
https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code
So if your LibGDX game has a function say, "setBluetooth" each platform will have its own implementation of said method. That will differ when you compile for Android or iOS.
If you try to call platform specific code in your core game probably won't work.
Hope it helps, maybe you have already done that in which case you can ignore my comment.
Related
I'm trying to send a simple string between Android device and a C# application
on android as client
Thread thread = new Thread() {
#Override
public void run() {
try {
Socket socket = new Socket("192.168.1.136",80);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("HELLO_WORLD");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
on the PC as a server using C#
byte[] byteReadStream = null;
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
TcpListener tcpl = new TcpListener(ipe);
while (true)
{
tcpl.Start();
TcpClient tcpc = tcpl.AcceptTcpClient();
byteReadStream = new byte[tcpc.Available];
tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
Console.WriteLine(Encoding.Default.GetString(byteReadStream) + "\n");
}
I have tried using specific IP and port it did not work
Bluetooth did not work
I have tried several posted codes on this site, all did not work. So maybe there this something that I am missing.
Please advice me on how to fix the code or a better way to send a string between android and windows app in any instant way.
After looking around some other posts.The problem was that as long as the USB is connected to the device that I'am using for debugging, it always gives host unreachable, remove the USB and then the code works.
I'am not sure if this was the same problem with Bluetooth.
I am looking to get/read the Data I passed after I connected a couple of Android Devices, so far I pair, connect and transmit the information between them, but not sure how to implement the reading part, here I am not sure if I should use createRfcommSocketToServiceRecord or listenUsingRfcommWithServiceRecord to create the reading socket for this purpose.
I have two screens, one where the user push a button and transmit the info and the other where the receiver press another button and read the data, I wonder if the sync is incorrect and after I push the "send" button and then the "read" button the connection is unavailable or if this implementation is just not recomendable all together.
These are my two attempts:
Attempt 1:
//Executed after the user press the read data button
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket serverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(device.getName(),uuid);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
BluetoothSocket clientSocket = serverSocket.accept();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
Attempt 2:
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);
//clientSocket without method and invoke is not working either
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
clientSocket = (BluetoothSocket) m.invoke(device, 1);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
clientSocket.connect();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
On serverSocket.accept() or clientSocket.connect() I get the exception:
Connection is not created, failed or aborted
I would appreciate if anyone could guide me towards getting the data reading part working. Thanks.
Take a look at Android's BluetoothChat example included with the Android SDK. I think it does exactly what you want.
$ANDROID_SDK/samples/android-19/legacy/BluetoothChat/src/com/example/android/BluetoothChat
Read the managing the connection part.
Its clearly written in the documentation how to exchange (read/write) info between devices through Bluetooth. http://developer.android.com/guide/topics/connectivity/bluetooth.html
I am developing board game in android. I want to make this game playable on two separate devices, for that I need to use WiFi-Direct. I want to know is there any library available which will help me to
Find and connect with device
Send and receive board coordinates between two devices after touch-listener event
I am interested in built-in library.
OR
If possible please share implemented example of client/server architecture.
This is for the server:
Thread serverThread = new Thread(new Runnable() {
#Override
public void run() {
try {
serverSocketTCP = new ServerSocket();
serverSocketTCP.setReuseAddress(true);
serverSocketTCP.bind(new InetSocketAddress(YourPort));
while (status) {
clientSocketTCP = serverSocketTCP.accept();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(client.getInputStream()));
OutputStream outputStream = client.getOutputStream();
}
} catch (Exception e) {
e.printStackTrace();
}
});
serverThread.start();
This is for the client:
Socket clientSocket = new Socket(ServerIP,ServerPort);
outputStream = clientSocket.getOutputStream();
bufferedReader=newBufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
Make the device that starts the game run as a TCP server and make it broadcast on the network and listen on a predetermined port. When another player wants to join, he just selects the server from a menu and join the game. The coordinates can be sent as packets on touch events.
I am learning a tutorial about how to consume json web service.
But I have two doubts can you please help me in understanding.
I am learning from this link
http://codeoncloud.blogspot.in/2013/05/blackberry-java-json-tutorial.html
Here is one class extend by thread
public class ConnectJson extends Thread {
private String url;
public String response;
private String myinterface = ";interface=wifi";
public void run() {
HttpConnection conn = null;
InputStream in = null;
int code;
try {
conn = (HttpConnection) Connector.open(this.url + this.myinterface, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while (-1 != (len = in.read(buffer))) {
out.write(buffer);
}
out.flush();
this.response = new String(out.toByteArray());
if (out != null){
out.close();
}
if (in != null){
in.close();
}
if (conn != null){
conn.close();
}
}
} catch (Exception e) {
Dialog.inform(e.toString());
}
}
public String jsonResult(String url){
this.url = url;
this.start();
this.run();
return response;
}
}
It is making one object of that class and call method of that class .In that method it call start as well as run method why ?
this.start();
this.run();?
In that method it call start as well as run method why ?
You'd have to ask the author of the code; looking at that class's code, it looks incorrect. It's also fairly unusual.
In the normal course of things, you don't call run directly; you start the thread (with start) and the JVM is then responsible for creating a new thread and calling run on it.
You can call run yourself if you really want that code to run right away on the current thread, but it's unusual and that class doesn't immediately look like it's designed to do that correctly. What that code actually does is start a new thread (which means run will eventually get called on that new thread), but then as you observed it also calls run directly. So run will run twice, and may well run twice simultaneously. Since the code in run uses instances variables that will be used by both threads but doesn't do anything to coordinate access to those instance variables...well, again, it looks incorrect.
I don't think I'd keep following that tutorial. You may find the Concurrency trail in the Java tutorials from Oracle might be useful. (Threads are part of it.)
I am working to add Bluetooth capabilities to my app and ultimately the device that I want to use is a headset/earpiece. I have begun assembling the code and I partial functionality with it. When I got to the code for setting up a bluetooth connection by server, I got errors when adding the code. I have tried solving the problems through the hover over the error and autocorrect but every time I fix one problem a different on arises. This leads me to believe that I am missing something that autocorrect doesn't know about. I need some help fixing the errors. Useful suggestions for setting a bluetooth codin for the first time would also be appreciated. Errors are surrounded with ||#| xxx |||. Error 1:cannot be resolved. Error 2:cannot be resolved to a variable. Error 3:undefined for the type AcceptSocket.
import java.io.IOException;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
public class AcceptSocket extends Thread {
private static final String MY_UUID = null;
BluetoothServerSocket mmServerSocket;
public void AcceptThread() {
// Use a temporary object that is later asssigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = ||1|mBluetoothAdapter|||.listenUsingRfcommWithServiceRecord(||2|NAME|||,
MY_UUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
||3|manageConnectedSocket|||(socket);
mmServerSocket.close();
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
}
}
}
Error 1,2: There is no constant called NAME anywhere in the class.
Error 3: There is no method called manageConnectedSocket() in the class.
You can't just copy and paste something from the developer's page and expect it to work. It leads you in the correct direction and you have to fill in the missing pieces.