james
james

Reputation: 1035

how to use another thread to stop NetworkOnMainThreadException?

I am trying to access the android network by starting a TCP server. But when I create a new thread, either by Thread t = new Thread(runnable); t.start();

or FutureTask I still get the networkonmainthreadexception...

Upvotes: 1

Views: 120

Answers (2)

droidchef
droidchef

Reputation: 2307

Use AsyncTask to perform network related ops

For Example :

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      return response;
    }

    @Override
    protected void onPostExecute(String result) {
      textView.setText(result);
    }
  } 

Or you can do this, Although it is not recommended

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = 
                new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        }

adding this code will not give you network on main thread exception anymore.

Upvotes: 2

Gabe Sechan
Gabe Sechan

Reputation: 93561

You have to do the actual network IO on the run() function of the runnable in the thread. You don't just create a thread and then do the IO.

Upvotes: 1

Related Questions