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

后端 未结 4 1433
刺人心
刺人心 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:54

    First, you need permission to know whether the device is connected to the web or not. This needs to be in your manifest, in the element:

    then

    ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    
    if (connec != null && (
        (connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) || 
        (connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED))) { 
    
            //You are connected, do something online.
    
    } else if (connec != null && (
        (connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) ||
        (connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED ))) {            
    
            //Not connected.    
            Toast.makeText(getApplicationContext(), "You must be connected to the internet", Toast.LENGTH_LONG).show();
    
    } 
    

提交回复
热议问题