stealthcopter / AndroidNetworkTools

Set of useful android network tools
Apache License 2.0
1.39k stars 282 forks source link

NetworkOnMainThreadException on Ping #29

Closed WindWZQ closed 6 years ago

WindWZQ commented 6 years ago

I'm using the ping with url.But give me a NetworkOnMainThreadException.

Here's the code:

private void doPing() {
    try {
        Ping.onAddress("www.baidu.com").setTimeOutMillis(1000).setTimes(5).doPing(new Ping.PingListener() {
            @Override
            public void onResult(PingResult pingResult) {
                Log.e(TAG, "onResult: " + pingResult.toString());
            }

            @Override
            public void onFinished(PingStats pingStats) {
                Log.e(TAG, "onFinished: " + pingStats.toString());
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
gelbertgel commented 6 years ago

I have same issue. If you add these lines, it solves.

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy);
stealthcopter commented 6 years ago

Ah this is because onAddress("www.baidu.com") will have to be resolved and will cause a network request. I will fix this in the next version.

stealthcopter commented 6 years ago

Should be fixed in 0.4.0 release, please reopen if not