Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2015 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.tv.util;
     18 
     19 import android.net.ConnectivityManager;
     20 import android.net.NetworkInfo;
     21 import android.support.annotation.Nullable;
     22 import android.support.annotation.WorkerThread;
     23 import java.io.IOException;
     24 import java.net.HttpURLConnection;
     25 import java.net.URL;
     26 
     27 /** A utility class to check the connectivity. */
     28 @WorkerThread
     29 public class NetworkUtils {
     30     private static final String GENERATE_204 = "http://clients3.google.com/generate_204";
     31 
     32     /** Checks if the internet connection is available. */
     33     public static boolean isNetworkAvailable(@Nullable ConnectivityManager connectivityManager) {
     34         if (connectivityManager == null) {
     35             return false;
     36         }
     37         NetworkInfo info = connectivityManager.getActiveNetworkInfo();
     38         if (info == null || !info.isConnected()) {
     39             return false;
     40         }
     41         HttpURLConnection connection = null;
     42         try {
     43             connection = (HttpURLConnection) new URL(GENERATE_204).openConnection();
     44             connection.setInstanceFollowRedirects(false);
     45             connection.setDefaultUseCaches(false);
     46             connection.setUseCaches(false);
     47             if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
     48                 return true;
     49             }
     50         } catch (IOException e) {
     51             // Does nothing.
     52         } finally {
     53             if (connection != null) {
     54                 connection.disconnect();
     55             }
     56         }
     57         return false;
     58     }
     59 
     60     private NetworkUtils() {}
     61 }
     62