2014年2月25日 星期二

Android - NetworkOnMainThreadException


Situation:

private void connect() {

    String device_URL = "http://tw.yahoo.com/";

    HttpURLConnection urlc;

    try {

        urlc = (HttpURLConnection) new URL(device_URL).openConnection();

        urlc.connect();

        Log.e("POST", urlc.getResponseMessage());

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

}


It will cause "NetworkOnMainThreadException" when you try to connect the Internet.


Reason of this situation:

In case of the connection is too long, the screen is gonna block in the main thread.
Solution 1:

Ignore the policy, just add few code in below.
(Not recommend and it's only provide android SDK version 9 or highter)

private void ignoreNetworkPolicy() {

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

        StrictMode.setThreadPolicy(policy);
    }
}


Solution 2:

Use thread.

public void createConnectThread() {

    Thread thread = new Thread(new Runnable() {

        @Override

	public void run() {
		request();
        }

    });

    thread.start();
}


Note:
If you want to update UI in thread, it will not permit because Android only allow main thread can update UI. The solution of this is "Handler".

private void updateUI() {

    Handler handler = new Handler();

    handler.post(new Runnable() {

        @Override

	public void run() {
		mTextView.setText("123");
	}
    });
}

Reference:
解决android.os.NetworkOnMainThreadException

沒有留言:

張貼留言