【发布时间】:2015-10-19 18:55:24
【问题描述】:
我正在尝试获取用户连接到网络的那一刻,然后我认为BroadcastReceiver 是一个好方法......我想做的是,当用户连接到网络时知道是否此网络已连接到 Internet。
最重要的是知道 WiFi 是否需要 Browse Log in 示例:Handling Network Sign-On 文档
到目前为止我尝试过什么?
我已经把我的BroadcastReceiver 改成了这个
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
Log.d("Network", "Internet YAY");
} else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) {
if (isNetworkOnline()) {
Log.d(TAG, String.valueOf(tikis));
NetTask TeInternet = new NetTask();
TeInternet.execute("https://www.google.com");
}
}
问题是当我尝试连接到没有Internet Connection 的WiFi 时,输入是这样的:
D/Network﹕ Internet YAY
D/Network﹕ Internet YAY
D/Network﹕ Internet YAY
D/RequiresLoginBroadcast﹕ 1 //this occurs sometimes
根据Handling Network Sign-On 文档,我已将Inner Class 更改为此
doInBackground()方法:
protected Boolean doInBackground(String...params) {
boolean internetAccessExists = false;
String urlToBeAccessed = params[0];
final int TIMEOUT_VALUE_IN_MILLISECONDS = 15000;
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urlToBeAccessed);
urlConnection = (HttpURLConnection) url.openConnection();
//set the respective timeouts for the connection
urlConnection.setConnectTimeout(TIMEOUT_VALUE_IN_MILLISECONDS);
urlConnection.setReadTimeout(TIMEOUT_VALUE_IN_MILLISECONDS);
//the redirect check is valid only after the response headers have been received
//this is triggered by the getInputStream() method
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (!url.getHost().equals(urlConnection.getURL().getHost())) {
internetAccessExists = true;
}
}
//any sort of exception is considered as a redirect.
//more specific exceptions such as SocketTimeOutException and IOException can be handled as well
catch (Exception e) {
Log.d(TAG, e.toString());
} finally {
Log.d(TAG, "Finally");
urlConnection.disconnect();
}
return internetAccessExists;
到目前为止我一直在寻找什么?
- How to detect when WIFI Connection has been established in Android?
- Android WIFI How To Detect When Specific WIFI Connection is Available
- BroadcastReceiver is not working (detect if wifi is connected)
还有更多......但遗憾的是我没有找到正确的答案。
TL;DR
我正在尝试做的事情是获取用户连接到网络的确切事件,然后找到一个很好的方法来检测我是否可以进行 google ping 或检查是否有连接到 Internet (仅限 WIFI,不允许 3G 连接),因为我现在使用的代码有时会失败...
我认为这是了解是否存在 Internet Connection 的好方法,因为我想知道的是检测 Wifi 是否需要浏览器登录。
我们差不多完成了...但我不明白为什么在BroadcastReceiver 上输入 4 次甚至 5 次...。有时说有 Internet connection 而没有...
【问题讨论】:
-
它是否检查网络是否连接?.....
-
您可以尝试 ping google,然后如果失败,则无法上网 :)
-
我想他是这么想的(“其次,我想只有在网络可用时才调用它。如果它不可用,我不想得到通知......)
标签: android