Issue
I want to build some connection between my android and the server (in my PC) via Java sockets. Simply, it just send data such as string and integer over the local network.
I read about the AsyncTask class. I added my socket connection code in the doInBackground()
method in the class (the class named RemoteClient
). Here is the code to connect and initialize the connection via socket:
@Override
protected Void doInBackground(Void... arg0) {
Log.i("Socket","Connecting to the remote server: " + host);
try{
socket = new Socket(host,8025);
oos = new ObjectOutputStream(socket.getOutputStream());
}catch(IOException ex){
ex.printStackTrace();
}
return null;
}
Simply i just want to make a method sendInteger(int value)
to the server via the socket. I already finished the connection, it connects well.
So, where should I put the sendInteger(int value)
method, can I just put the method in the RemoteClient
class along with the implemented methods?
I want to call the sendInteger(int value)
methods when a button is clicked.
Thank you..
Solution
Yes you can just put the sendInteger inside of your AsyncTask. I like to use the Constructor instead of the AsyncTask Parameters, because it is more flexibel. You can implement an interface as a callback to receive the server answer inside your UI. onPostExecute will always called by the system just after onBackground was executed. onPostExecute runs also on the UI Thread so you don't have to deal with coming back to your UI Thread since your AsyncTask will run on a different thread.
Your code would look like this:
Fragmentclass or Activity:
private void onButtonClick() {
...
RemoteClient rc = new RemoteClient(value, (response) -> {
Log.d(response);
};
rc.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
...
}
public class RemoteClient extends AsyncTask<Void, Void, Void> {
private Callback callback;
private int intValue;
public RemoteClient(int intValue, Callback callback) {
this.callback = callback;
this.intValue = intValue;
}
@Override
protected Void doInBackground(Void... arg0) {
Log.i("Socket","Connecting to the remote server: " + host);
try{
socket = new Socket(host,8025);
oos = new ObjectOutputStream(socket.getOutputStream());
sendInteger(intvalue);
} catch(IOException ex){
ex.printStackTrace();
}
return null;
}
private void sendInteger(int value) {
// send the integer
}
protected void onPostExecute(Void aVoid) {
if (callback != null) {
callback.response;
}
}
private interface Callback {
void serverResponse(String value);
}
}
If you want to be more fliexble you can implement a NetworkManager class which just starts your Async Task. Then you can always pass a String as JSON to your AsyncTask. Or you just use AsyncTask but then i would recommend to use inheritance.
Answered By - Erythrozyt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.