问题
I'm building an application with my team for a robot car to let it drive controlled by a mobile device. It works perfectly on my phone, but now that I've ported the app to Android Wear, the thread that lets me connect to a server on my Raspberry Pi doesn't work. Is there a way to get this thread working?
Code:
public class SocketConnect {
static DataOutputStream dOut;
static Socket socket;
public static void connect() {
System.out.println("Got to Connect");
new Thread() {
public void run() {
try {
socket = new Socket("192.168.2.9", 8899);
System.out.println("Trying at 2.9");
dOut = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
....further code
Logcat error: http://pastebin.com/0BtF27p8 (couldn't get it to format nice in the editor)
回答1:
Two problems with your approach:
- NetworkOnMainThreadException - you can't do network operations on the main (UI) thread on Android 4.0+ devices
- Android Wear devices cannot directly connect to any internet address - you have to use the Wearable Data Layer to send information to the phone app and have it connect/pass information to a server
In many cases, including what you'd want to do for controlling a robot car, you'd probably want to use messages to transfer a lightweight command from the Watch to your phone app.
来源:https://stackoverflow.com/questions/26598498/android-wear-doesnt-start-thread