-2

I ve made an app that targets 19-25 API, and i use sockets to send and recieve messages. All versions of android works fine but Nougat crashes.

In my activitie i open a new thread to work with Sockets Output and Input, from that thread i update UI thread with handlers and im creating buttons with listeners which send messages (output.println("...")). Everything is ok but when my app runs on Nougat and the user press a button it crashes:

    FATAL EXCEPTION: main
                    Process: com.exmple, PID: ####
                    android.os.NetworkOnMainThreadException
                  android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                  at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
                  ....

And it points into my Thread/button.Listener/output.println(""); line.

When im using a new thread for sending messages inside the thread then it doesnt crash but the messages are corrupted. CODE:

    public class MainActivity extends AppCompatActivity {
      @Override
      protected void onCreate(Bundle savedInstanceState) {
       //some code...
      }
     public void GoLobby(View view) {
       Thread thread =new Thread(new watcher(Timer,ask,......));
       thread.start();
     }

THREAD CODE:

    public class watcher implements Runnable {
     Socket socket;
     PrintWriter output;
     BufferedReader input;
     public watcher(TextView TimerRef,Spinner askRef,.....){
       //some parameters....
       //....buttons code
       Start.setOnClickListener(new View.OnClickListener(){
         @Override
         public void onClick(View v){
            output.println("START");// <-- ERROR POINTS HERE
            //IF I PUT IT IN A NEW THREAD IS OK BUT IS TOO SLOW AND I HAVE PROBLEMS WITH WHAT I SEND
            Start.setVisibility(View.INVISIBLE);
         }
       });
     }
      //some other buttons...

     @Override
     public void run() {
        boolean connected=false;
        try{
            socket = new Socket(Host, Port);
            output = new PrintWriter(socket.getOutputStream(), true);
            input = new BufferedReader(new 
            InputStreamReader(socket.getInputStream()));
            connected=true;
            if(connected){
                 sender.init(output);
                 Log.i(TAG,"ini snd/threa");
            }
        }catch (IOException e) {

        }
        //waiting messsages and updating UI with Handlers
never give
  • 13
  • 6
  • https://stackoverflow.com/questions/6343166/how-to-fix-android-os-networkonmainthreadexception – Nishant Rajput Jun 14 '17 at 08:36
  • try to use Async Task. – Yuvaraja Jun 14 '17 at 08:36
  • The exception that is thrown when an application attempts to perform a networking operation on its main thread. read this https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html – 배준모 Jun 14 '17 at 08:26
  • Your onClick listener will be called from the UI thread so any network code you put in there will throw this exception. You will have to come up with another strategy for getting your thread to perform the network operations when you click the button. – Dave Rager Jun 14 '17 at 13:04

1 Answers1

0

A very good explanation here: How to fix android.os.NetworkOnMainThreadException?

In a nutshell (though dupped on this site):
This exception is raised when you try to perform network operations, which are potentially long, on the main UI thread. The effect of lengthy operations on the UI thread is bad responsiveness.

Consider the following example: you're designing an app that sends 20M file to a remote server when the user clicks a button. If the network operation to send these 20M is performed on the main UI thread, that thread will be busy sending 20M of data instead of handling user interactions. This means the entire UI will not be responsive until that network operation is done...

Use an AsyncTask or a separate thread to perform network operations

Ishay Peled
  • 2,783
  • 1
  • 23
  • 37