Broadcastreceiver para detectar la red está conectado

Estoy tratando de obtener el momento en que el usuario se conecta a una red, entonces pensé que un BroadcastReceiver es un buen enfoque … Lo que me gustaría hacer es, cuando el usuario se conecta a una red de saber si esta red tiene conexión a Internet.

Lo principal también es saber si el WiFi requiere Browse Log in Ejemplo: Handling Network Sign-On documentación

¿Qué he intentado hasta ahora?

He cambiado mi BroadcastReceiver a este

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

El problema es que cuando intento conectarme a un WiFi sin Internet Connection la entrada es la siguiente:

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

He cambiado la Inner Class a esto de acuerdo con la documentación de Handling Network Sign-On

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; 

¿Qué he buscado hasta ahora?

  1. ¿Cómo detectar cuándo se ha establecido la conexión WIFI en Android?
  2. Android WIFI Cómo detectar cuándo está disponible una conexión WIFI específica
  3. BroadcastReceiver no funciona (detecte si el wifi está conectado)

Y más … pero tristemente no encontré la respuesta correcta para mí.

TL, DR

Lo que estoy tratando de hacer es obtener el evento exacto que los usuarios se conecta a una red y luego obtener un buen método para detectar si puedo hacer un ping de google o para comprobar si hay conexión a Internet (SOLAMENTE CON WIFI, 3G CONEXIÓN NO ES PERMITIDA) , porque el código que estoy usando en este momento está fallando a veces …

Creo que este es un buen método para saber si hay una Internet Connection ya que lo que quiero saber es detectar si Wifi Requiere Inicio de sesión del navegador.

Estamos casi terminados … Pero no entiendo por qué está entrando en el BroadcastReceiver 4 veces o incluso 5 …. ya veces diciendo que hay Internet connection cuando no hay …

Esto es lo que estoy usando actualmente, y está funcionando perfectamente. Me notifican cuando el Internet está conectado (no sólo encendido, cuando hay una conexión real a Internet).
También funciona para cualquier tipo de conexión de datos, pero puede modificarse fácilmente para aceptar sólo WiFi, 3G, 4G, etc.

Código:

 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 :("); } } } } 

Manifiesto:

 <receiver android:name=".receivers.NetworkReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> 
 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(); } } } 

}

Conjunto de manifiesto

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

Todo lo que necesita se describe en este documento: Determinación y supervisión del estado de la conectividad . También echa un vistazo a esta clase: Connectivity.java .

En pocas palabras, los pasos deben ser los siguientes:

1. Intercepte la transmisión CONNECTIVITY_CHANGE .

2. En el método onReceive() , compruebe si hay conectividad a Internet y si es Wifi o GPRS.

Esto debe ser fácil de implementar, y debe funcionar sin problemas. En algunos casos, al igual que con HTC y algunos dispositivos Samsung, el comportamiento puede variar si se ha modificado el SO principal.

Cada vez que revise la intenet usando Broadcast Receiver

Introduzca aquí la descripción de la imagen

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/> <receiver android:name=".receivers.NetworkChangeReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> =============================================================== package com.keshav.networkchangereceiverexample.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import static com.keshav.networkchangereceiverexample.MainActivity.dialog; public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { if (isOnline(context)) { dialog(true); Log.e("keshav", "Online Connect Intenet "); } else { dialog(false); Log.e("keshav", "Conectivity Failure !!! "); } } catch (NullPointerException e) { e.printStackTrace(); } } private boolean isOnline(Context context) { try { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); //should check null because in airplane mode it will be null return (netInfo != null && netInfo.isConnected()); } catch (NullPointerException e) { e.printStackTrace(); return false; } } } ================================================================= package com.keshav.networkchangereceiverexample; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.ConnectivityManager; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.TextView; import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver; public class MainActivity extends AppCompatActivity { private BroadcastReceiver mNetworkReceiver; static TextView tv_check_connection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_check_connection=(TextView) findViewById(R.id.tv_check_connection); mNetworkReceiver = new NetworkChangeReceiver(); registerNetworkBroadcastForNougat(); } public static void dialog(boolean value){ if(value){ tv_check_connection.setText("We are back !!!"); tv_check_connection.setBackgroundColor(Color.GREEN); tv_check_connection.setTextColor(Color.WHITE); Handler handler = new Handler(); Runnable delayrunnable = new Runnable() { @Override public void run() { tv_check_connection.setVisibility(View.GONE); } }; handler.postDelayed(delayrunnable, 3000); }else { tv_check_connection.setVisibility(View.VISIBLE); tv_check_connection.setText("Could not Connect to internet"); tv_check_connection.setBackgroundColor(Color.RED); tv_check_connection.setTextColor(Color.WHITE); } } private void registerNetworkBroadcastForNougat() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } } protected void unregisterNetworkChanges() { try { unregisterReceiver(mNetworkReceiver); } catch (IllegalArgumentException e) { e.printStackTrace(); } } @Override public void onDestroy() { super.onDestroy(); unregisterNetworkChanges(); } } ============================================================== activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.keshav.networkchangereceiverexample.MainActivity"> <TextView android:id="@+id/tv_check_connection" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Connection establised !" android:padding="25dp" app:layout_constraintBottom_toBottomOf="parent" android:gravity="center" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </LinearLayout> 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.