Java tutorial
//package com.java2s; /* * Copyright (C) 2012 Andrew Neal Licensed under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class Main { /** * Used to determine if there is an active data connection and what type of * connection it is if there is one * * @param context The {@link Context} to use * @return True if there is an active data connection, false otherwise. * Also, if the user has checked to only download via Wi-Fi in the * settings, the mobile data and other network connections aren't * returned at all */ public static final boolean isOnline(final Context context) { /* * This sort of handles a sudden configuration change, but I think it * should be dealt with in a more professional way. */ if (context == null) { return false; } boolean state = false; final boolean onlyOnWifi = true;//PreferenceUtils.getInstace(context).onlyOnWifi(); /* Monitor network connections */ final ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); /* Wi-Fi connection */ final NetworkInfo wifiNetwork = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wifiNetwork != null) { state = wifiNetwork.isConnectedOrConnecting(); } /* Mobile data connection */ final NetworkInfo mbobileNetwork = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mbobileNetwork != null) { if (!onlyOnWifi) { state = mbobileNetwork.isConnectedOrConnecting(); } } /* Other networks */ final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); if (activeNetwork != null) { if (!onlyOnWifi) { state = activeNetwork.isConnectedOrConnecting(); } } return state; } }