I am confused as to how I can achieve something and how it should be done as I believe there is more than one method;
I have an app and at the start it establishes a TCP connection to a server, then every now and again lets pretend you press a button and send a string to the server. Really the connection (I’ve used java.net.Socket) should run in a separate thread out of the main UI thread (which is where it currently is).
I have a public method so when the button is pressed, the method is called, and the data sent but again this runs from the main UI thread. Since the connection is constant throughout the life cycle of the app it should probably be an intent service, but can you have a call’able method within an intent service to send the data in the back ground over the back ground connection?
Or a service which connects the socket in the onStart() method and then within the service implement an asynctask? I’m lost!
You can use
synchronizedto perform that, for example (and this is just a scratch of course, not handling any exception):And in your activity (MyActivity.java) you add:
after the connection is established, the client will check if new data to send available, and if not, it will wait to notify. Also, you might find this question useful
EDIT:
Since it’s too much for a comment, I edited my answer.
You have to start the tcpClient thread from somewhere, right? So do it from your activity. This way you’ll have the object of the thread (as we used it in
myListener). regardingnotify()– this is meaningless when we are not talking about threads (If I’m wrong, please someone correct me) and it’s purpose is to “free” threads that are on wait because of the same object to continue in execution, in this case is the client thread itself(synchronized(this)) so we tell it to continue, and just before that, we change the condition in the loop to be true (in the methodsetData(String)) so it will now send the data, and go into wait mode again.