I have connected my android phone with LAN connection. I would like to display a toast or an alert when I disable LAN connection. I am trying the following code but its of no use. What am I missing ?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isNetworkAvailable(MainActivity.this);
}
// to check connection state
public static boolean isNetworkAvailable(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if(networkCapabilities == null){
Toast.makeText(context, "No Internet connection!", Toast.LENGTH_LONG).show();
}
return true;
}
}
I couldn't Use NetworkInfo
since its been deprecated. Thanks in advance
UPDATE:
I solved my problem using the example from the link below. Very well explained. Have a look :)