0

I'm trying to connect a socket with Android. I know that you can't open network-connections from MainThread. I have created an AsyncTask to do it. I have created and private class inside of the main class, I have seen some examples on internet about that.

Could someone help me about what it's wrong?? I guess that it's a error in the way I'm trying to connect because I have connected to the server with a normal Java class. I have edited the manisfest to give the necessary permissions.

If someone has any advise about a better way to do it, it would be great.

public class MainActivity extends Activity {

    private ObjectInputStream input;
    private ObjectOutputStream output;          
    private Button buttonCreateRoom;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonCreateRoom = (Button)findViewById(R.id.buttonCreate);


        //buttons       
        buttonCreateRoom.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                onClickButton(ConstantsRooms.CREATE_ROOM);
            }
        });


    }

    private void onClickButton(int numberButton){
        RequestMessage request = null;

        switch (numberButton) {
            ....
        }

        AsyncButtons asyncButtons = new AsyncButtons();
        asyncButtons.execute(request);  

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }




    //Botones
   private class AsyncButtons extends AsyncTask<RequestMessage, ResponseMessage, Void> {
        private Socket socket;

        @Override
        protected Void doInBackground(RequestMessage... params) {
            RequestMessage request;
            ResponseMessage response;
            Void v = null;
            try{

                request = params[0];                    
                output.writeObject(request);
                output.flush();     

                response = (ResponseMessage)input.readObject();

            ...
        } 


        @Override
        protected void onPreExecute() {

            try{
                // Setup networking
                **socket = new Socket(ConstantsRooms.SERVER_ADDRESS, ConstantsRooms.PORT_PUBLIC); -->ERROR**
                socket.setTcpNoDelay(true);
                output = new ObjectOutputStream(socket.getOutputStream());
                output.flush();
                input = new ObjectInputStream(socket.getInputStream());

            }catch (Exception exp){
                Log.e(TAG, "Excepcion socket ---");
                exp.printStackTrace();
            }
        }           
    }

}
Guille
  • 2,186
  • 3
  • 22
  • 40

2 Answers2

1

According to doc here

onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

Do your network things in doInBackground

stinepike
  • 52,673
  • 14
  • 90
  • 109
0

onPreExecute() in invoked on the UI thread. So creating socket connection in onPreExecute causes NetWorkOnMainThreadException. Move that part of the code to doInbackground()

Move the try catch in onPreExecute() to doInbackground()

For more information check the doc in the below link especially the topic under The 4 steps

http://developer.android.com/reference/android/os/AsyncTask.html

Raghunandan
  • 131,557
  • 25
  • 223
  • 252