Display an alert when internet connection not available in android application

后端 未结 13 779
有刺的猬
有刺的猬 2020-12-08 11:48

In my application data comes from internet and I am trying to create a function that checks if a internet connection is available or not and if it isn\'t, it gives an alert

13条回答
  •  情书的邮戳
    2020-12-08 12:06

    public boolean isOnline() {
        ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
    
        if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
            Toast.makeText(context, "No Internet connection!", Toast.LENGTH_LONG).show();
            return false;
        }
    return true; 
    }
    

    And you must add premission for accessing network state and Internet:

    
    
    

提交回复
热议问题