0

Im having issues with Sockets and Threads in API 25. Im directly targeting API 25 on my Nexus 6p with 7.1.1

When trying to communicate with my node server on port 8124 I initialize a new thread and initialize a socket but I either get a networkonmainthreadexception

public class MainActivity extends AppCompatActivity {

private Socket socket;

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

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy);

    Button LoginButton = (Button) findViewById(R.id.button2);
    LoginButton.setOnClickListener(
            new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    TryLogin(v);
                }
            }
    );
}

public void TryLogin(View v){
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                socket = new Socket("192.168.1.57", 8124);
                Log.i("SOCKET", "Was the thread started?");
            } catch(UnknownHostException e1){

            } catch (IOException e1){

            }
        }
    }).start();
}

}

When I call start() I never see "Was the thread started?". Neither is any error thrown in logcat. But when I change to run() i get networkonmainthreadexception error. It seams as if something was changed. Ive verified that tcp connections to my node server show up using a node client.

2 Answers2

1

This exception is thrown when application attempts to perform a networking operation in the main thread. Use below code in your onViewCreated to avoid this error otherwise use AsynkTask for your network call.

  if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }
Jaimin Prajapati
  • 341
  • 5
  • 14
0

When you get networkonmainthreadexception, it means your thread has started correctly and the only reason your Log.i isn't being printed out, is because the error is thrown before the printing. Move your Log.i above the socket code like this and you'll see it being printed:

Log.i("SOCKET", "Was the thread started?");
socket = new Socket("192.168.1.57", 8124);

Now knowing that your thread started up correctly, you can focus on the main issue which is networkmainthreadexception.

And luckily, the answer to that issue is here: How to fix android.os.NetworkOnMainThreadException?

Hope this helps!

Community
  • 1
  • 1
DiderDrogba344
  • 534
  • 8
  • 17
  • Okay I get the Log message now but I dont see a connection in my node console. Neither do I see an error with e1.printStackTrace() on IoException or UnknowHostException – lzRipTide3zl Apr 20 '17 at 06:36
  • didn't you say networkonmainthreadexception was the error being thrown? You can fix that by running that socket code in an AsyncTask. More on that can be found here: http://stackoverflow.com/questions/6343166/how-to-fix-android-os-networkonmainthreadexception – DiderDrogba344 Apr 20 '17 at 06:38
  • Add another catch for Exception that only logs and rethrows. I guess it will be a different exception type than the two you are catching. – Fildor Apr 20 '17 at 06:41
  • Well it was throwing the main thread expection when i was doing run() but now it logs the message im getting a Connection Time out error which is weird because I can get a connection with a node client but not android – lzRipTide3zl Apr 20 '17 at 06:42
  • Run your socket code from an AsyncTask and report back results. – DiderDrogba344 Apr 20 '17 at 06:47
  • `didn't you say networkonmainthreadexception was the error being thrown? You can fix that by running that socket code in an AsyncTask.`. Nonsense. OP is using a thread already. An async task will not change anything. – greenapps Apr 20 '17 at 07:35
  • `I can get a connection with a node client but not android `??? Dont understand. Where is that node client running? And you do not mean android but your android client app? – greenapps Apr 20 '17 at 07:38
  • What you said greenapps makes sense. I was simply going with what he said. "I change to run() i get networkonmainthreadexception error" because if according to what you said, networkonmainthreadexception should've never even been thrown at all. And with regards to the node client he's running, he's simply saying that he was able to connect to node.js backend with a node client. In other words, he's saying there's nothing wrong with the backend but something wrong with the android client. – DiderDrogba344 Apr 20 '17 at 07:40
  • Thanks, I got it to work. I changed my node listen line form '127.0.0.1' to '0.0.0.0' and I got connections from the app – lzRipTide3zl Apr 20 '17 at 23:27
  • np, glad I could help! – DiderDrogba344 Apr 21 '17 at 00:35