gpt4 book ai didi

java - 检查 Android 上的互联网连接

转载 作者:行者123 更新时间:2023-11-30 03:41:32 26 4
gpt4 key购买 nike

我需要在 Android 应用程序上检查互联网连接。

我正在使用这段代码:

 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni!=null && ni.isAvailable() && ni.isConnected()) {
return true;
} else {
return false;
}

并且无法传递下一个错误:

The method getSystemService(String) is undefined for the type ConxsMTD

我尝试使用 getContext().getSystemService,但也失败并出现下一个错误:

The method getContext() is undefined for the type ConxsMTD

知道我做错了什么吗?

最佳答案

这并不能解决您给定的示例,但我的示例确实有效并且更简单(在我看来)。

您要做的是发送“ping”(如果您想这样称呼)来检查连接。如果连接完成,您就知道您仍然处于连接状态。如果您收到 IOExceptionNullPointerException,那么您可能超时并且不再连接。

try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
urlConnect.setConnectTimeout(1000);
urlConnect.getContent();
System.out.println("Connection established.");
} catch (NullPointerException np) {
np.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
}

关于java - 检查 Android 上的互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15622247/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com