BroadcastReceiver的检测网络连接 [英] Broadcastreceiver to detect network is connected

查看:184
本文介绍了BroadcastReceiver的检测网络连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让在那里用户连接到网络上的那一刻,我想到了一个的BroadcastReceiver 是一个很好的办法......我想事情做的是,当用户连接到网络知道这个网络具有连接到因特网。

最主要的也就是知道,如果无线网络要求浏览登录例如:<$c$c>Handling网络点登录 文档

我到目前为止已经试过?

我改变了的BroadcastReceiver

 如果(intent.getAction()。等于(ConnectivityManager.CONNECTIVITY_ACTION)){
的NetworkInfo的NetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
如果(的NetworkInfo = NULL和放大器;!&安培; networkInfo.getDetailedState()== NetworkInfo.DetailedState.CONNECTED){
    Log.d(网络,互联网YAY);
}否则,如果(的NetworkInfo = NULL和放大器;!&安培; networkInfo.getDetailedState()== NetworkInfo.DetailedState.DISCONNECTED){
    如果(isNetworkOnline()){
        Log.d(TAG,将String.valueOf(tikis));
        NetTask TeInternet =新NetTask();
        TeInternet.execute(https://www.google.com);


    }
}
 

现在的问题是,当我尝试连接到一个无线没有 Internet连接输入是这样的:

  D /网络:互联网YAY
D /网络:互联网YAY
D /网络:互联网YAY
D / RequiresLoginBroadcast:1 //这有时会发生
 

我已经改变了内部类此acording用的<$c$c>Handling网络点登录 文档

doInBackground()方法:

 保护布尔doInBackground(字符串... PARAMS){
布尔internetAccessExists = FALSE;
串urlToBeAccessed = PARAMS [0];
最终诠释TIMEOUT_VALUE_IN_MILLISECONDS = 15000;
URL网址;
HttpURLConnection类的URLConnection = NULL;
尝试 {
    URL =新的URL(urlToBeAccessed);
    的URLConnection =(HttpURLConnection类)url.openConnection();
    //设置各自超时的连接
    urlConnection.setConnectTimeout(TIMEOUT_VALUE_IN_MILLISECONDS);
    urlConnection.setReadTimeout(TIMEOUT_VALUE_IN_MILLISECONDS);
    //重定向检查是有效的已收到响应报头后,才
    //这是由触发的getInputStream()方法
    InputStream的时间=新的BufferedInputStream(urlConnection.getInputStream());
    如果(!url.getHost()。等于(urlConnection.getURL()。GETHOST())){
        internetAccessExists = TRUE;
    }
}
//任何种类的异常被认为是重定向。
//更具体的例外,如SocketTimeoutException如果和IOException异常可以处理,以及
赶上(例外五){
    Log.d(TAG,e.toString());
} 最后 {
    Log.d(TAG,最后);
    urlConnection.disconnect();
}
返回internetAccessExists;
 

我看什么这么远吗?

  1. <一个href="http://stackoverflow.com/questions/5888502/how-to-detect-when-wifi-connection-has-been-established-in-android">How检测时,WiFi连接已建立的Andr​​oid?
  2. <一个href="http://stackoverflow.com/questions/9353005/android-wifi-how-to-detect-when-specific-wifi-connection-is-available">Android WIFI如何检测当具体WIFI连接可用
  3. <一个href="http://stackoverflow.com/questions/24314577/broadcastreceiver-is-not-working-detect-if-wifi-is-connected">BroadcastReceiver不工作(检测,如果无线连接)

和更多...但saddly我没有找到正确的答案给我。

TL; DR

这是我想要做的事情是得到确切的事件的用户连接到网络,然后得到一个很好的方法来检测,如果我可以做一个谷歌ping或检查是否有连接互联网的 (仅限于WIFI,3G连接是不允许的),因为我使用目前的code有时失败......

我觉得这是一个很好的方法,要知道,如果有一个 Internet连接,因为我想知道的是检测是否需要无线浏览器登录的东西。

我们的任务基本上完成...但我不明白为什么进入的的BroadcastReceiver 4倍甚至5 ....有时说有 Internet连接时,有没有...

解决方案

这是我目前使用,它的工作完美。我得到通知时,作为连接互联网(不只是打开,当有一个实际的连接到互联网)。
它也适用于任何类型的数据连接,但可以很容易被修改为只接受的WiFi,3G,4G等。

code:

 公共类NetworkReceiver扩展的BroadcastReceiver {

    @覆盖
    公共无效的onReceive(上下文的背景下,意图意图){
        如果(intent.getAction()。等于(ConnectivityManager.CONNECTIVITY_ACTION)){
            的NetworkInfo的NetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            如果(的NetworkInfo = NULL和放大器;!&安培; networkInfo.getDetailedState()== NetworkInfo.DetailedState.CONNECTED){
                Log.d(网络,互联网YAY);
            }否则,如果(的NetworkInfo = NULL和放大器;!&安培; networkInfo.getDetailedState()== NetworkInfo.DetailedState.DISCONNECTED){
                Log.d(网络,没有互联网:();
            }
        }
    }
}
 

清单:

 &LT;接收器
    机器人:名称=receivers.NetworkReceiver。&GT;
    &LT;意向滤光器&gt;
        &lt;作用机器人:名称=android.net.conn.CONNECTIVITY_CHANGE/&GT;
    &所述; /意图滤光器&gt;
&LT; /接收器&GT;
 

I'm trying to get the moment where user connects to a network, then I thought a BroadcastReceiver is a good approach... The thing that I would like to do is, when user connects to a network know if this network has connection to Internet.

The main thing also is know if the WiFi requires Browse Log in Example : Handling Network Sign-On documentation

What I've tried so far?

I've changed my BroadcastReceiver to this

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");


    }
}

The problem is that when I try to connect to a WiFi without Internet Connection the input is this :

D/Network﹕ Internet YAY
D/Network﹕ Internet YAY
D/Network﹕ Internet YAY
D/RequiresLoginBroadcast﹕ 1 //this occurs sometimes

I've changed the Inner Class to this acording with the Handling Network Sign-On documentation

doInBackground() method:

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;

What I've looked for so far?

  1. How to detect when WIFI Connection has been established in Android?
  2. Android WIFI How To Detect When Specific WIFI Connection is Available
  3. BroadcastReceiver is not working (detect if wifi is connected)

And more... but saddly I didn't find the correct answer to me.

TL;DR

The thing that I'm trying to do is get the exact event that users connects to a network and then get a good method to detect if I can make a google ping or to check if is there connection to Internet (ONLY WITH WIFI, 3G CONNECTION IS NOT ALLOWED), because the code that I'm using at the moment is failing sometimes...

I think this is a good method to know if there is an Internet Connection since the thing that I want to know is detect if Wifi Requires Browser Login.

We are almost done... But I don't get why is entering on the BroadcastReceiver 4 times or even 5.... and sometimes saying that there's Internet connection when there is not...

解决方案

This is what i'm currently using, and it's working perfectly. I get notified when the internet as connected (not just turned on, when there's an actual connection to the internet).
It also works for any kind of data connection, but can easily be modified to only accept WiFi, 3G, 4G, etc.

Code:

public class NetworkReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        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) {
                Log.d("Network", "No internet :(");
            }
        }
    }
}

Manifest:

<receiver
    android:name=".receivers.NetworkReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

这篇关于BroadcastReceiver的检测网络连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆