By Manfred Moser


2011-03-01 04:57:09 8 Comments

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 ;-) ??

5 comments

@KeLiuyue 2017-09-22 07:48:16

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);
}

@Dharmendra Pratap 2016-05-20 13:46:40

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.

@David Wasser 2016-10-21 14:23:09

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().

@Mustafa Güven 2011-10-05 20:51:31

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.

@David Wasser 2016-10-21 14:24:50

Using Handler doesn't necessarily solve the problem. The default behaviour of Handler also executes on the main (UI) thread.

@Manoj Kumar 2012-08-16 06:49:26

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

@WarrenFaith 2013-09-05 15:11:03

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...

@Manfred Moser 2011-03-04 20:56:18

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.

@Jeremy Edwards 2011-03-05 18:28:17

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."

@Alex Lockwood 2012-08-02 15:14:40

Read my blog post on the NetworkOnMainThreadException for more information. It explains why this occurs on Android 3.0 and above.

Related Questions

Sponsored Content

3 Answered Questions

3 Answered Questions

[SOLVED] InetAddress.getByName causes NetworkOnMainThreadException

  • 2012-10-05 15:30:59
  • Octoth0rpe
  • 4088 View
  • 1 Score
  • 3 Answer
  • Tags:   android runnable

4 Answered Questions

[SOLVED] NetworkOnMainThreadException in AsyncTask

1 Answered Questions

[SOLVED] NetworkOnMainThreadException with AsyncTask

3 Answered Questions

[SOLVED] Quick fix for NetworkOnMainThreadException

1 Answered Questions

[SOLVED] Android AsyncTask and NetworkOnMainThreadException

Sponsored Content