Checking internet connection with service on android

后端 未结 3 2116
时光取名叫无心
时光取名叫无心 2020-12-31 19:39

I know how to check for internet connectivity when my app is open using activity. But how to check for connectivity in service when my app is not running?

3条回答
  •  耶瑟儿~
    2020-12-31 20:28

    Using below code you can test whether device is connected with internet or not. You can use this function anytime when you try to call any webservice or any task related to internet. You can use this function in android service which runs in background.

    public boolean isConnectingToInternet(Context _context){
            ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
              if (connectivity != null)
              {
                  NetworkInfo[] info = connectivity.getAllNetworkInfo();
                  if (info != null)
                      for (int i = 0; i < info.length; i++)
                          if (info[i].getState() == NetworkInfo.State.CONNECTED)
                          {
                              return true;
                          }
    
              }
              return false;
        }
    

提交回复
热议问题