1

我正在尝试使用服务通过套接字连接到服务器。但由于某些原因,它无法连接到它,在这一行返回 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 服务对此有好处。

谢谢你的帮助 !

4

2 回答 2

0

当网络请求与任何特定活动无关时,在服务中执行网络操作是一个好主意。但是无论服务是在同一个进程中还是在不同的进程中运行,它的生命周期方法仍然在它的“主”线程上调用。省去直接使用 AsyncTasks 的麻烦,并使用像 android-async-http 这样封装它们的库。

于 2014-05-26T16:47:12.530 回答
0

您需要将代码放在其他线程中建立连接的位置(尝试使用asyncTask)

阅读文档 http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

于 2014-05-26T16:24:28.893 回答