Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Broadcastreceiver to detect network is connected

Tags:

android

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...

like image 404
Skizo-ozᴉʞS Avatar asked Jul 29 '15 00:07

Skizo-ozᴉʞS


People also ask

What does a BroadcastReceiver do?

A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.

How do I check if BroadcastReceiver is registered?

Currently there is no way to check if a receiver is registered using the receiver reference. You have to unregister the receiver and catch the IllegalArgumentException that is thrown if it's not registered.

When would you use a BroadcastReceiver?

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.


2 Answers

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>
like image 140
Moonbloom Avatar answered Oct 17 '22 10:10

Moonbloom


public abstract class NetworkReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (null != intent) {
        State wifiState = null;  
        State mobileState = null;  
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
        wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();  
        mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();  
        if (wifiState != null && mobileState != null  
                && State.CONNECTED != wifiState  
                && State.CONNECTED == mobileState) {  
            // phone network connect success
            gNetwork();
        } else if (wifiState != null && mobileState != null  
                && State.CONNECTED != wifiState  
                && State.CONNECTED != mobileState) {  
            // no network
            noNetwork();
        } else if (wifiState != null && State.CONNECTED == wifiState) {  
            // wift connect success
            WIFINetwork();
        }
    }
}

}

manifest set

 <receiver android:name=".receiver.AssistantReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>
like image 10
leo Avatar answered Oct 17 '22 12:10

leo