携帯電話のネットワーク環境に関するコード


 IP、MAC, , wifi 


public class NetworkUtil {

	/**
	 *  IP
	 * 
	 * @return
	 */
	public static String getIpAddress() {
		try {
			Enumeration<NetworkInterface> enumeration = NetworkInterface
					.getNetworkInterfaces();
			while (enumeration.hasMoreElements()) {
				NetworkInterface nextElement = enumeration.nextElement();
				Enumeration<InetAddress> enIp = nextElement.getInetAddresses();
				while (enIp.hasMoreElements()) {
					InetAddress ipaddress = enIp.nextElement();
					if (!ipaddress.isLoopbackAddress()) {
						return ipaddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 *  
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isConnect(Context context) {
		//  ( wi-fi,net )
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				//  
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					//  
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		} catch (Exception e) {
			Log.v("====", e.toString());
		}
		return false;
	}

	/**
	 *  MAC 
	 * 
	 * @param ctx
	 * @return
	 */
	public static String getMacAddress(Context ctx) {
		WifiManager wfMgr = (WifiManager) ctx
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wfMgr.getConnectionInfo();
		return info.getMacAddress();
	}

	/**
	 *  wifi 
	 * 
	 * @param ctx
	 * @return
	 */
	public static String getNetWorkStatus(Context ctx) {
		WifiManager wfMgr = (WifiManager) ctx
				.getSystemService(Context.WIFI_SERVICE);
		int state = wfMgr.getWifiState();
		String status = null;
		switch (state) {
		case WifiManager.WIFI_STATE_DISABLED:
			status = " (DISABLED)";
			break;
		case WifiManager.WIFI_STATE_DISABLING:
			status = " (DISABLING)";
			break;
		case WifiManager.WIFI_STATE_ENABLED:
			status = " (ENABLED)";
			break;
		case WifiManager.WIFI_STATE_ENABLING:
			status = " (ENABLING)";
			break;
		case WifiManager.WIFI_STATE_UNKNOWN:
			status = " (UNKNOWN)";
			break;
		}
		WifiInfo info = wfMgr.getConnectionInfo();
		status += " AP MAC(" + info.getBSSID() + ") DBM (" + info.getRssi()
				+ ")";
		return status;
	}

}