Skip to content

Instantly share code, notes, and snippets.

@oscarcidcoder
Last active November 14, 2018 16:11
Show Gist options
  • Save oscarcidcoder/0a075e36b4712eddbe3fd92def887031 to your computer and use it in GitHub Desktop.
Save oscarcidcoder/0a075e36b4712eddbe3fd92def887031 to your computer and use it in GitHub Desktop.
Connection Changes Android

⚠️ Manifest

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

⚠️ API < 24

public BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
  
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting() &&
                activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

  
        String connectionMsg = isConnected ? "Red disponible" : "Red no disponible";
        Log.d("MainActivity", connectionMsg);
    }
};

//ACTIVITY
@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectionReceiver, filter);
}

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

⚠️ API >= 24

@Override
protected void onStart() {
    super.onStart();

    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mNetworkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                Toast.makeText(MainActivity.this,
                        "Conexión disponible",
                        Toast.LENGTH_LONG).show();
            }

    
            @Override
            public void onLost(Network network) {
                Toast.makeText(MainActivity.this,
                        "Conexión perdida",
                        Toast.LENGTH_LONG).show();
            }
        };
        mConnectivityManager.registerDefaultNetworkCallback(mNetworkCallback);
    } 
}

@Override
protected void onStop() {
    super.onStop();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mConnectivityManager.unregisterNetworkCallback(mNetworkCallback);
    } 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment