我是android和java的新手,并试图创建ping服务以通过我的android应用程序检查网站的状态。我已经尝试了关于stackoverflow的几乎所有解决方案,并在Google上进行了搜索,但对我而言似乎没有任何锻炼。我只希望通过android studio / java的ping服务来检查网站的状态(工作/关闭),例如“ www.google.com”
我正在模拟器nexus_s_API_29上的android studio上运行代码
public boolean hostAvailable(String host, int port) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), 2000);
Log.i(TAG,"*********Success *********** ");
return true;
} catch (IOException e) {
// Either we have a timeout or unreachable host or failed DNS lookup
Log.i(TAG,"error "+e);
return false;
}
}
//then calling this on main activity onCreate() method
hostAvailable("www.google.com", 80);
我希望输出的网站是打开或关闭,但出现这样的错误
2019-07-14 13:14:10.922 6251-6251/com.example.portalping E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.portalping, PID: 6251
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.portalping/com.example.portalping.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3268)