Detect whether network is available or not - Android Network

Android examples for Network:Network Status

Description

Detect whether network is available or not

Demo Code


//package com.java2s;
import android.content.Context;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import android.util.Log;

public class Main {
    public static final String TAG = "CLDeviceUtil";

    /**/*from   w w w.  j av  a2s.  c o  m*/
     * Detect whether network is available or not
     * 
     * @return if WIFI or GRPS is available, return YES, else return NO
     * @author Sean Zheng
     * @CreateDate 2013-4-24
     */
    public static boolean isConnectNetWork(final Context context) {
        boolean result = false;
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        boolean isWifiConnected = cm.getNetworkInfo(
                ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ? true
                : false;
        NetworkInfo mobileState = cm
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean isGprsConnected = false;
        if (mobileState != null) {
            isGprsConnected = mobileState.getState() == NetworkInfo.State.CONNECTED ? true
                    : false;
        }
        Log.d(TAG, "wifi connected:" + isWifiConnected + " gps connected:"
                + isGprsConnected);
        result = isWifiConnected || isGprsConnected ? true : false;
        return result;
    }
}

Related Tutorials