How can i check whether an android device is connected to the web?

后端 未结 4 1442
刺人心
刺人心 2020-12-03 06:54

How would i know whether my device is connected the web or not? How can i detect connectivity? Any sample code?

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 07:51

    Add this permission in your AppManifest.xml file:

    
    

    The method to check if network is available or not:

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

    Source

提交回复
热议问题