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 
24 import java.io.IOException;
25 import java.net.HttpURLConnection;
26 import java.net.URL;
27 
28 /**
29  * A utility class to check the connectivity.
30  */
31 @WorkerThread
32 public class NetworkUtils {
33     private static final String GENERATE_204 = "http://clients3.google.com/generate_204";
34 
35     /**
36      * Checks if the internet connection is available.
37      */
isNetworkAvailable(@ullable ConnectivityManager connectivityManager)38     public static boolean isNetworkAvailable(@Nullable ConnectivityManager connectivityManager) {
39         if (connectivityManager == null) {
40             return false;
41         }
42         NetworkInfo info = connectivityManager.getActiveNetworkInfo();
43         if (info == null || !info.isConnected()) {
44             return false;
45         }
46         HttpURLConnection connection = null;
47         try {
48             connection = (HttpURLConnection) new URL(GENERATE_204).openConnection();
49             connection.setInstanceFollowRedirects(false);
50             connection.setDefaultUseCaches(false);
51             connection.setUseCaches(false);
52             if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
53                 return true;
54             }
55         } catch (IOException e) {
56             // Does nothing.
57         } finally {
58             if (connection != null) {
59                 connection.disconnect();
60             }
61         }
62         return false;
63     }
64 
NetworkUtils()65     private NetworkUtils() { }
66 }
67