我正在尝试使用服务通过套接字连接到服务器。但由于某些原因,它无法连接到它,在这一行返回 NetworkOnMainThreadException
socket = new Socket(SERVER_IP, SERVERPORT);
我已经在清单中添加了权限和服务。
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;
}
}
这是使用绑定服务的好方法吗?我想在许多活动中使用此服务,并且在 Android 文档中,它说使用 Bound 服务对此有好处。
谢谢你的帮助 !