I'm trying to use a service to connect to a server with a socket. But for some reasons, it cannot connect to it returning a NetworkOnMainThreadException at this line
socket = new Socket(SERVER_IP, SERVERPORT);
I have already added Permission and the service in the manifest.
public class SocketService extends Service{
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
private Socket socket = null;
private DataInputStream in;
private DataOutputStream out;
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
SocketService getService() {
// Return this instance of LocalService so clients can call public methods
return SocketService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
/** method for clients */
public Socket getSocket() {
return socket;
}
public InputStream getDataInputStream() throws IOException {
return socket.getInputStream();
}
public OutputStream getDataOutputStream() throws IOException {
return socket.getOutputStream();
}
@Override
public void onCreate(){
String SERVER_IP = "10.0.2.2";
int SERVERPORT = 8080;
try {
socket = new Socket(SERVER_IP, SERVERPORT);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
} catch (Exception ex) {
Log.e("Erreur","Connexion impossible !");
ex.printStackTrace();
}
}
@Override
public void onDestroy(){
super.onDestroy();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String sendMessage(String message) {
String response = "";
try {
out.writeBytes(message + "\n");
out.flush();
response = this.in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
}
Is it the good way to do it using a Bound service ? I would like to use this service in many activities, and in the Android documentation, it says that using a Bound service is good for that.
Thanks for your help !
you need to put the code where the connection is made in other thread(try to use asyncTask)
read a documentation http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html