我正在尝试获取用户连接到网络的时刻,于是我想到了使用BroadcastReceiver
的方法... 我想要做的事情是,当用户连接到一个网络时,知道这个网络是否连接到互联网。
另外一个主要的问题是,要知道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
根据网络登录处理文档,我已将内部类
更改为以下内容:
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;
我到目前为止寻找的是什么?
还有更多...但可悲的是我没有找到适合我的正确答案。
简短总结
我正在尝试获取用户连接到网络的确切事件,然后找到一种好方法来检测是否可以进行 Google Ping 或检查是否有 Internet 连接(仅限 WIFI,不允许 3G 连接),因为我目前正在使用的代码有时会出现故障...
我认为这是了解是否存在Internet 连接
的好方法,因为我想知道的是是否需要浏览器登录以检测 WIFI。
我们快要完成了......但我不明白为什么会进入 BroadcastReceiver
4 次甚至 5 次...有时候会说有 Internet 连接
,但实际上没有...
wifi
连接还是互联网
连接? - Darpan