Detect if Android device has Internet connection

后端 未结 15 2730
野性不改
野性不改 2020-11-22 08:54

I need to tell if my device has Internet connection or not. I found many answers like:

private boolean isNetworkAvailable() {
    ConnectivityManager connect         


        
15条回答
  •  鱼传尺愫
    2020-11-22 09:56

    You can do this using the ConnectivityManager API for android. It allows you to check whether you are connected to the internet and the type of internet connection you are connected to. Basically, Metered or Un-metered.

    To check for internet connection.

    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    

    Documentation link: https://developer.android.com/training/monitoring-device-state/connectivity-status-type

提交回复
热议问题