Get network access info. - Android Network

Android examples for Network:Network Status

Description

Get network access info.

Demo Code


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

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

public class Main {
    private static final String ACCESS_WIFI = "Wi-Fi";
    private static final String ACCESS_MOBILE = "Mobile";

    /**//from w ww  . j a  v a2 s .c  om
     * Get network access info.
     * @param context The context of the application.
     * @return The network access info.
     */
    public static String[] getNetworkAccessInfo(Context context) {
        String[] accessInfo = { "", "" };
        try {
            PackageManager packageManager = context.getPackageManager();
            if (!checkPermissionGranted(context,
                    "android.permission.ACCESS_NETWORK_STATE")) {
                accessInfo[0] = "";
                return accessInfo;
            }

            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager == null) {
                accessInfo[0] = "";
                return accessInfo;
            }

            NetworkInfo wifiNetworkInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiNetworkInfo != null
                    && wifiNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
                accessInfo[0] = ACCESS_WIFI;
                return accessInfo;
            }

            NetworkInfo mobileNetworkInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mobileNetworkInfo != null
                    && mobileNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
                accessInfo[0] = ACCESS_MOBILE;
                accessInfo[1] = mobileNetworkInfo.getSubtypeName();
                return accessInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return accessInfo;
    }

    private static boolean checkPermissionGranted(Context context,
            String permission) {
        PackageManager packageManager = context.getPackageManager();
        if (packageManager.checkPermission(permission,
                context.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }
}

Related Tutorials