31

I just found out about NetworkOnMainThreadException at official docs

and was wondering if the emulator is throwing this. I have been testing my app quite a bit and as far as I know all networking is off the main thread (using Roboguice RoboAsyncTask) but you never know if one has not escaped.

I am also using StrictMode and have not seen anything.

  1. Is my code just clean or is this not thrown on the emulator?

  2. How are we supposed to prepare for this happening in production?

  3. What about a grace period or something? Or is that elapsed now ;-) ??

Mr.Me
  • 9,192
  • 5
  • 39
  • 51
Manfred Moser
  • 29,539
  • 13
  • 92
  • 123
  • 1
    This was introduced in Android 3.0. I got it when i was doing a network operation on the UI thread, as the documentation states. I moved and run the operation on a separate thread and it was gone. – Samuh Mar 01 '11 at 05:10
  • You get it in the emulator too or just with a device? Without StrictMode enabled? – Manfred Moser Mar 01 '11 at 06:01
  • I got it on the emulator without running in StrictMode. – Samuh Mar 03 '11 at 09:43
  • It should not be hard to intentionally cause this if you want to be sure that it's going to result in an error message. – Chris Stratton Aug 08 '11 at 19:59
  • @Samuh may i ask which version of android emulator u were using when u get NetworkOnMainThreadException? cause I could not reproduce this erro on the emulator at all. Thanks! – sammiwei Apr 25 '12 at 00:04
  • Read this [blog post on the **`NetworkOnMainThreadException`**](http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html) for more information... it's very helpful! – Alex Lockwood Jul 31 '12 at 21:25

5 Answers5

13

With honeycomb you can not perform a networking operation on its main thread as documentation says. For this reason you must use handler or asynctask. There is no another way to do it.

here you can find 2 examples written in turkish about networking operation. maybe they help.

Mustafa Güven
  • 15,526
  • 11
  • 63
  • 83
  • Using `Handler` doesn't necessarily solve the problem. The default behaviour of `Handler` also executes on the main (UI) thread. – David Wasser Oct 21 '16 at 14:24
5

I have tested this and it does in fact happen on the emulator as well. Better make sure you test your app at least on the emulator if you plan to get it onto the 3.0 tablets and beyond.

Manfred Moser
  • 29,539
  • 13
  • 92
  • 123
  • 2
    The docs say this: "This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness." – Jeremy Edwards Mar 05 '11 at 18:28
  • 1
    **[Read my blog post on the `NetworkOnMainThreadException` for more information.](http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html)** It explains why this occurs on Android 3.0 and above. – Alex Lockwood Aug 02 '12 at 15:14
2

NetworkOnMainThreadException occurs when some networking operations are performed inside main method; I mean Oncreate(). You can use AsyncTask for resolving this issue. or you can use

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

inside onCreate() method.

UrsinusTheStrong
  • 1,239
  • 1
  • 16
  • 33
  • 1
    This is wrong. The exception is thrown when performing Network I/O on the **main Thread**. This can happen in any method, not just in `onCreate()`. – David Wasser Oct 21 '16 at 14:23
1

If you are running on 3.0, i can't help; Because Strict mode is on by default in it; But its above tat, then this might help

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

Include this before your HTTP connection creation; Then it works

Manoj Kumar
  • 1,510
  • 3
  • 20
  • 40
  • 6
    old answer, but please be assured: It is the wrong way to do! Do never ever any network stuff on the UI thread. A kitten will die for every millisecond of delay you cause with that... – WarrenFaith Sep 05 '13 at 15:11
1

From Honeycomb SDK (3), Google will no longer allow network requests (HTTP, Socket) and other related operations directly in the Main Thread class, in fact, should not do direct network operation in the UI thread, blocking UI, user experience is bad! Even if Google is not prohibited, under normal circumstances, we will not do it ~! So, that is, in the Honeycomb SDK (3) version, you can also continue to do so in Main Thread, more than 3, it will not work.

1.use Handler

The more time-consuming operations associated with network are placed into a child thread and then communicated with the main thread using the Handler messaging mechanism

public static final String TAG = "NetWorkException";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_net_work_exception);
    // Opens a child thread, performs network operations, waits for a return result, and uses handler to notify UI
    new Thread(networkTask).start();
}

Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        // get data from msg and notify UI
        Bundle data = msg.getData();
        String val = data.getString("data");
        Log.i(TAG, "the result-->" + val);
    }
};

/**
 * net work task
 */
Runnable networkTask = new Runnable() {

    @Override
    public void run() {
        // do here, the HTTP request. network requests related operations
        Message msg = new Message();
        Bundle data = new Bundle();
        data.putString("data", "request");
        msg.setData(data);
        handler.sendMessage(msg);
    }
};

2.use AsyncTask

public static final String TAG = "NetWorkException";
private ImageView mImageView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_net_work_exception);
    mImageView = findViewById(R.id.image_view);
    new DownImage(mImageView).execute();
}


class DownImage extends AsyncTask<String, Integer, Bitmap> {

    private ImageView imageView;

    public DownImage(ImageView imageView) {
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        String url = params[0];
        Bitmap bitmap = null;
        try {
            //load image from internet , http request here
            InputStream is = new URL(url).openStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        // nodify UI here
        imageView.setImageBitmap(result);
    }
}

3.use StrictMode

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42