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

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

    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:

    
    

    Next, you need to get a reference to the ConnectivityManager:

    ConnectivityManager cm = (ConnectivityManager) Context.getSystemService(Context.CONNECTIVITY_SERVICE);
    

    From there you need to obtain a NetworkInfo object. For most, this will mean using ConnectivityManager. getActiveNetworkInfo():

    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni == null) {
        // There are no active networks.
        return false;
    }
    

    From there, you just need to use one of NetworkInfo's methods to determine if the device is connected to the internet:

    boolean isConnected = ni.isConnected();
    

提交回复
热议问题