In my Android app I use a thread to download an image from the internet, but for some reason when I run the app on my galaxy nexus a networkonmainthread exception is thrown but not if I run the app in the emulator (tested Android Versions 2.3.3 and 4.0.3).
Thread ImageLoaderThread = new Thread(new Runnable() {
public void run() {
bitmap= DrawableManager.fetchDrawable(URL);
});
Because the GUI starts slowly when I start the thread directly on start-up I get the impression, that the thread indeed runs on the GUI thread…but why???
It depends on how you build. You are building using Honeycomb SDK (for Android 3.0 and higher) when building for the device.
NetworkOnMainThreadExceptionis never thrown with older SDKs.You are not using the same SDK for the emulator, at least not when building to test on 2.3.3. If you use the same build configuration when testing on 2.3.3 and 4.0.3, that would completely explain all the results you are seeing.
Accessing the network on the main thread was never considered good practice (the concern is UI responsiveness as no other thread can serve the UI while you are waiting for network to respond), but it was not strictly banned in the API until Honeycomb.
Read this tutorial to move your network access into an
AsyncTask.