16

I run into a NetworkOnMainThreadException with my Android 3.0 app. Searching for a solution I found this, but if I understand this correctly, default setting would be that the strict mode is turned off.

Also, all my network access is in an AsyncTask, so I don't see the point in this Exception anyway.

So, I'm quite desperate now what I should do to prevent this...

Kind regards, jellyfish

Edit:

This blog entry says that AsyncTask should be enough, but at least clarifies the StrictMode point.

Solution:

I turned off the StrictMode (its probably better to keep some settings but I couldn't be bothered...):

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

After that, I did run into a "java.lang.RuntimeException: This thread forbids HTTP requests", but found a solution for this here. I'm a bit confused, though, as AndroidHttpClient worked fine when I used it in my Android 2.0+ app...

Solution, part2

As it turned out, using AsyncTask was a nice idea but pretty useless if done wrong... So there was nothing wrong with the strict mode's reaction. Should have listened, er? ;)

Still good to know it's activated on Honeycomb by default.

Community
  • 1
  • 1
jellyfish
  • 7,228
  • 11
  • 34
  • 49

2 Answers2

14

In Android Honeycomb StrictMode is enabled, turn it off adding the code on the onCreate() function...

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);       
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
Jorgesys
  • 114,263
  • 22
  • 306
  • 247
  • This code may be the correct way to change the policy, but it's almost always the wrong way to handle `NetworkOnMainThreadException`. If you check the OP's update, you'll see that they were just improperly using `AsyncTask`. But, `AsyncTask`, or some other mechanism of getting network traffic off the UI thread, is basically always a better solution than this policy change hack. – Nate Feb 08 '13 at 10:25
5

StrictMode is turned on by default in Honeycomb.

See say link specifically penaltyDeathOnNetwork(). I ran into a similar problem.

PJL
  • 18,057
  • 16
  • 68
  • 66
  • Thank you... this new API is driving me crazy. ^^ I don't get it why an AsyncTask isn't considered to be out of the main thread... – jellyfish Jun 09 '11 at 08:05
  • I agree. What's wrong with Thread.run()? Why do they even need that? – Chloe Mar 27 '12 at 07:05