Detect if Android device has Internet connection

后端 未结 15 2742
野性不改
野性不改 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:36

    The latest way to do that from the documentation is to use the ConnectivityManager to query the active network and determine if it has Internet connectivity.

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

    Add these two permissions to your AndroidManifest.xml file:

    
    
    

提交回复
热议问题