Ejemplo de Android de oyente de Internet

I am working on an Android app that will continuously remain connected to Internet. If Internet is dow, it should give an appropriate message to the User.

Is there any thing like Internet Listener? Or how to implement this event that whenever Internet connection is not available it should give alert.

preguntado el 28 de agosto de 12 a las 11:08

2 Respuestas

Create one Broadcast Receiver for that and register it in manifest file.

First create a new class NetworkStateReceiver and extend BroadcastReceiver.

public class NetworkStateReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
     Log.d("app","Network connectivity change");
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            Log.i("app","Network "+ni.getTypeName()+" connected");
        }
     }
     if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
            Log.d("app","There's no network connectivity");
     }
   }
}

Put this code in your AndroidManifest.xml under the "application" element:

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

Y agrega este permiso

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

EDITAR

This code just detects connectivity change but cannot tell whether the network it is connected to has a internet access. Use this method to check that -

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
    Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

Respondido 30 ago 14, 05:08

I have tried this solution but this not working dude. also gives error at super.onReceive(context, intent); - Zeeshan Chaudhry

O yes its done Don't know wats the problem have to restart Emulator to make "F8" Work. Thanks alot @Chirag Raval Stay Blessed buddy - Zeeshan Chaudhry

EXTRA_NETWORK_INFO is deprecated. Here's a workaround stackoverflow.com/a/20590138/1939564 - muhammad babar

From Android 7.0, you can't really register a BroadcastReceiver statically that can listen for Connectivity change. - policíasencarretera

The code from Chirag Raval above certainly works. The trouble is that the listener will get invoked even when the application is not running in foreground.

IMHO, the better approach is to register / unregister the receiver in the onResume() / onPause() methods of all your application activities. This code should do it:

private final NetworkStateReceiver stateReceiver = new NetworkStateReceiver();

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    registerReceiver(stateReceiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(stateReceiver);
}

Obviously, remove the registration from AndroidManifest.xml archivo.

Using this solution, the receiver will be called also when switching between activities of your application (assuming you are closing them). In such a case, use a static flag (being shared between all your activities) like in the example below (called online):

public class NetworkStateReceiver extends BroadcastReceiver {

    private static boolean online = true;  // we expect the app being online when starting

    public static final String TAG = NetworkStateReceiver.class.getSimpleName();

    public void onReceive(Context context, Intent intent) {
        Log.d(TAG,"Network connectivity change");
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = manager.getActiveNetworkInfo();
        if (ni == null || ni.getState() != NetworkInfo.State.CONNECTED) {
            Log.d(TAG,"There's no network connectivity");
            if (online) // don't show the message if already offline
                Toast.makeText(context, R.string.noInternet, Toast.LENGTH_SHORT).show();
            online = false;
        } else {
            Log.d(TAG,"Network "+ni.getTypeName()+" connected");
            if (!online)  // don't show the message if already online
                Toast.makeText(context, R.string.backOnline, Toast.LENGTH_SHORT).show();
            online = true;
        }
    }
}

If starting your app when being offline, the Toast message will appear; otherwise it appears only when losing / re-establishing the connection .

Respondido 04 Abr '17, 12:04

Would this work when the internet is connected and the strength is weakening(not disconnected) - Kuldeep Bhimte

@KuldeepBhimte not really; it only works when an event is triggered; check here: stackoverflow.com/questions/1206891/… - pepan

Cool, Worked Like a Charm Seems easier than registering Intent in AndroidManifest.xml - Rahul Shyokand

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.