Skip to content Skip to sidebar Skip to footer

The Code Socket Clientsocket = New Socket(); Crashes In Android App. Why?

I am using a standard client code to send a string to my server. It works perfect when I am running a java project from eclipse but it doesn't work when I am running the same code

Solution 1:

Because you do it from the main thread, you have move it to a Thread.

new Thread(new Runnable(){
    publicvoidrun(){
        //open socket
    }
}).start();

Next you have to add the internet permission on the AndroidManifest

<uses-permissionandroid:name="android.permission.INTERNET" />

In android we can use AsyncTask witch can perform actions on main thread when the background operation is finished. It will be :

newAsyncTask<Void,Void,Void>(){

        @Overrideprotected Void doInBackground(Void... params) {
            String modifiedSentence;
            BufferedReaderinFromUser=newBufferedReader( newInputStreamReader(System.in));
            SocketclientSocket=newSocket("192.168.1.91", 6789);
            DataOutputStreamoutToServer=newDataOutputStream(clientSocket.getOutputStream());
            BufferedReaderinFromServer=newBufferedReader(newInputStreamReader(clientSocket.getInputStream()));
            sentence = "connection with android successful";
            outToServer.writeBytes(sentence + '\n');
            modifiedSentence = inFromServer.readLine();
            clientSocket.close();

            returnnull;
        }

        @OverrideprotectedvoidonPostExecute() {
            super.onPostExecute();
            Button button=(Button) k;
            ((Button) k).setText("Done");
        }
    }.execute();

Post a Comment for "The Code Socket Clientsocket = New Socket(); Crashes In Android App. Why?"