Example usage for android.net NetworkInfo getSubtypeName

List of usage examples for android.net NetworkInfo getSubtypeName

Introduction

In this page you can find the example usage for android.net NetworkInfo getSubtypeName.

Prototype

@Deprecated
public String getSubtypeName() 

Source Link

Document

Return a human-readable name describing the subtype of the network.

Usage

From source file:org.apache.cordova.core.NetworkManager.java

/**
 * Determine the type of connection// ww w .  j  a  v  a2s .  c o m
 *
 * @param info the network info so we can determine connection type.
 * @return the type of mobile network we are on
 */
private String getType(NetworkInfo info) {
    if (info != null) {
        String type = info.getTypeName();

        if (type.toLowerCase().equals(WIFI)) {
            return TYPE_WIFI;
        } else if (type.toLowerCase().equals(MOBILE)) {
            type = info.getSubtypeName();
            if (type.toLowerCase().equals(GSM) || type.toLowerCase().equals(GPRS)
                    || type.toLowerCase().equals(EDGE)) {
                return TYPE_2G;
            } else if (type.toLowerCase().startsWith(CDMA) || type.toLowerCase().equals(UMTS)
                    || type.toLowerCase().equals(ONEXRTT) || type.toLowerCase().equals(EHRPD)
                    || type.toLowerCase().equals(HSUPA) || type.toLowerCase().equals(HSDPA)
                    || type.toLowerCase().equals(HSPA)) {
                return TYPE_3G;
            } else if (type.toLowerCase().equals(LTE) || type.toLowerCase().equals(UMB)
                    || type.toLowerCase().equals(HSPA_PLUS)) {
                return TYPE_4G;
            }
        }
    } else {
        return TYPE_NONE;
    }
    return TYPE_UNKNOWN;
}

From source file:com.android.profilerapp.network.NetworkFragment.java

private Thread getStatisticThread() {
    return new Thread(new Runnable() {

        private Statistics statistics;
        private long[] myStartBytes;
        private long[] myBytes;

        private void initialize() {
            statistics = new Statistics();
            myStartBytes = getTrafficBytes(Integer.toString(myUid));
        }//from  ww w. j a v a2  s.c o  m

        @Override
        public void run() {
            initialize();
            while (!Thread.currentThread().isInterrupted()) {
                myBytes = getTrafficBytes(Integer.toString(myUid));
                statistics.sendBytesFromFile = myBytes[0] - myStartBytes[0];
                statistics.receiveBytesFromFile = myBytes[1] - myStartBytes[1];

                // Gets the bytes from API too, because API read is later than file read, API results may be a little larger.
                myBytes[0] = TrafficStats.getUidTxBytes(myUid) - myStartBytes[0];
                myBytes[1] = TrafficStats.getUidRxBytes(myUid) - myStartBytes[1];
                if (statistics.sendBytesFromFile > myBytes[0] || statistics.receiveBytesFromFile > myBytes[1]) {
                    Log.d(TAG, String.format(
                            "Bytes reported not in sync. TrafficStats: %1$d, %2$d, getTrafficBytes: %3$d, %4$d",
                            myBytes[0], myBytes[1], statistics.sendBytesFromFile,
                            statistics.receiveBytesFromFile));
                }

                NetworkInfo networkInfo = myConnectivityManager.getActiveNetworkInfo();
                statistics.networkName = networkInfo != null
                        && networkInfo.getSubtype() != TelephonyManager.NETWORK_TYPE_UNKNOWN
                                ? networkInfo.getSubtypeName()
                                : networkInfo.getTypeName();
                statistics.radioStatus = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
                        ? myConnectivityManager.isDefaultNetworkActive() ? "Radio high power"
                                : "Radio not high power"
                        : "Radio status unknown";
                statistics.openConnectionCount = getConnectionCount(Integer.toString(myUid));
                postStatistics(statistics);
                try {
                    Thread.currentThread().sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

From source file:disono.webmons.com.utilities.sensor.Connection.Network.java

/**
 * Type of connection//from   w ww.j a v  a2 s  . c  o  m
 *
 * @param info
 * @return
 */
private String type(NetworkInfo info) {
    if (info != null) {
        String type = info.getTypeName().toLowerCase(Locale.US);

        if (type.equals(WIFI)) {
            return TYPE_WIFI;
        } else if (type.toLowerCase().equals(TYPE_ETHERNET)
                || type.toLowerCase().startsWith(TYPE_ETHERNET_SHORT)) {
            return TYPE_ETHERNET;
        } else if (type.equals(MOBILE) || type.equals(CELLULAR)) {
            type = info.getSubtypeName().toLowerCase(Locale.US);

            if (type.equals(GSM) || type.equals(GPRS) || type.equals(EDGE) || type.equals(TWO_G)) {

                return TYPE_2G;
            } else if (type.startsWith(CDMA) || type.equals(UMTS) || type.equals(ONEXRTT) || type.equals(EHRPD)
                    || type.equals(HSUPA) || type.equals(HSDPA) || type.equals(HSPA) || type.equals(THREE_G)) {

                return TYPE_3G;
            } else if (type.equals(LTE) || type.equals(UMB) || type.equals(HSPA_PLUS) || type.equals(FOUR_G)) {

                return TYPE_4G;
            }
        }
    } else {
        return TYPE_NONE;
    }

    return TYPE_UNKNOWN;
}

From source file:Main.java

public static int getNetWorkType(Context context) {
    int netType = NETWORK_NO;
    NetworkInfo info = getActiveNetworkInfo(context);
    if (info != null && info.isAvailable()) {

        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            netType = NETWORK_WIFI;//  w  ww  .  ja  v a2 s.  c  o  m
        } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            switch (info.getSubtype()) {

            case NETWORK_TYPE_GSM:
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_IDEN:
                netType = NETWORK_2G;
                break;

            case NETWORK_TYPE_TD_SCDMA:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                netType = NETWORK_3G;
                break;

            case NETWORK_TYPE_IWLAN:
            case TelephonyManager.NETWORK_TYPE_LTE:
                netType = NETWORK_4G;
                break;
            default:

                String subtypeName = info.getSubtypeName();
                if (subtypeName.equalsIgnoreCase("TD-SCDMA") || subtypeName.equalsIgnoreCase("WCDMA")
                        || subtypeName.equalsIgnoreCase("CDMA2000")) {
                    netType = NETWORK_3G;
                } else {
                    netType = NETWORK_UNKNOWN;
                }
                break;
            }
        } else {
            netType = NETWORK_UNKNOWN;
        }
    }
    return netType;
}

From source file:com.example.testplayer.NetworkManager.java

/**
 * Determine the type of connection/*  w  ww. ja  va2s . co  m*/
 *
 * @param info the network info so we can determine connection type.
 * @return the type of mobile network we are on
 */
private String getType(NetworkInfo info) {
    if (info != null) {
        String type = info.getTypeName().toLowerCase(Locale.US);

        Log.d("CordovaNetworkManager", "toLower : " + type.toLowerCase());
        Log.d("CordovaNetworkManager", "wifi : " + WIFI);
        if (type.equals(WIFI)) {
            return TYPE_WIFI;
        } else if (type.toLowerCase().equals(TYPE_ETHERNET)) {
            return TYPE_ETHERNET;
        } else if (type.equals(MOBILE) || type.equals(CELLULAR)) {
            type = info.getSubtypeName().toLowerCase(Locale.US);
            if (type.equals(GSM) || type.equals(GPRS) || type.equals(EDGE)) {
                return TYPE_2G;
            } else if (type.startsWith(CDMA) || type.equals(UMTS) || type.equals(ONEXRTT) || type.equals(EHRPD)
                    || type.equals(HSUPA) || type.equals(HSDPA) || type.equals(HSPA)) {
                return TYPE_3G;
            } else if (type.equals(LTE) || type.equals(UMB) || type.equals(HSPA_PLUS)) {
                return TYPE_4G;
            }
        }
    } else {
        return TYPE_NONE;
    }
    return TYPE_UNKNOWN;
}

From source file:org.openchaos.android.fooping.service.PingService.java

@Override
protected void onHandleIntent(Intent intent) {
    String clientID = prefs.getString("ClientID", "unknown");
    long ts = System.currentTimeMillis();

    Log.d(tag, "onHandleIntent()");

    // always send ping
    if (true) {/*  www  .  j  a  v  a  2  s .  c  o  m*/
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "ping");
            json.put("ts", ts);

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
    // http://developer.android.com/reference/android/os/BatteryManager.html
    if (prefs.getBoolean("UseBattery", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "battery");
            json.put("ts", ts);

            Intent batteryStatus = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            if (batteryStatus != null) {
                JSONObject bat_data = new JSONObject();

                int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                if (level >= 0 && scale > 0) {
                    bat_data.put("pct", roundValue(((double) level / (double) scale) * 100, 2));
                } else {
                    Log.w(tag, "Battery level unknown");
                    bat_data.put("pct", -1);
                }
                bat_data.put("health", batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1));
                bat_data.put("status", batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1));
                bat_data.put("plug", batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1));
                bat_data.put("volt", batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1));
                bat_data.put("temp", batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1));
                bat_data.put("tech", batteryStatus.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY));
                // bat_data.put("present", batteryStatus.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false));

                json.put("battery", bat_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/guide/topics/location/strategies.html
    // http://developer.android.com/reference/android/location/LocationManager.html
    if (prefs.getBoolean("UseGPS", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "loc_gps");
            json.put("ts", ts);

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            Location last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (last_loc != null) {
                JSONObject loc_data = new JSONObject();

                loc_data.put("ts", last_loc.getTime());
                loc_data.put("lat", last_loc.getLatitude());
                loc_data.put("lon", last_loc.getLongitude());
                if (last_loc.hasAltitude())
                    loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
                if (last_loc.hasAccuracy())
                    loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
                if (last_loc.hasSpeed())
                    loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
                if (last_loc.hasBearing())
                    loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));

                json.put("loc_gps", loc_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("UseNetwork", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "loc_net");
            json.put("ts", ts);

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            Location last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (last_loc != null) {
                JSONObject loc_data = new JSONObject();

                loc_data.put("ts", last_loc.getTime());
                loc_data.put("lat", last_loc.getLatitude());
                loc_data.put("lon", last_loc.getLongitude());
                if (last_loc.hasAltitude())
                    loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
                if (last_loc.hasAccuracy())
                    loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
                if (last_loc.hasSpeed())
                    loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
                if (last_loc.hasBearing())
                    loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));

                json.put("loc_net", loc_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/reference/android/net/wifi/WifiManager.html
    if (prefs.getBoolean("UseWIFI", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "wifi");
            json.put("ts", ts);

            if (wm == null) {
                wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            }

            List<ScanResult> wifiScan = wm.getScanResults();
            if (wifiScan != null) {
                JSONArray wifi_list = new JSONArray();

                for (ScanResult wifi : wifiScan) {
                    JSONObject wifi_data = new JSONObject();

                    wifi_data.put("BSSID", wifi.BSSID);
                    wifi_data.put("SSID", wifi.SSID);
                    wifi_data.put("freq", wifi.frequency);
                    wifi_data.put("level", wifi.level);
                    // wifi_data.put("cap", wifi.capabilities);
                    // wifi_data.put("ts", wifi.timestamp);

                    wifi_list.put(wifi_data);
                }

                json.put("wifi", wifi_list);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // TODO: cannot poll sensors. register receiver to cache sensor data
    // http://developer.android.com/guide/topics/sensors/sensors_overview.html
    // http://developer.android.com/reference/android/hardware/SensorManager.html
    if (prefs.getBoolean("UseSensors", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "sensors");
            json.put("ts", ts);

            if (sm == null) {
                sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            }

            List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ALL);
            if (sensors != null) {
                JSONArray sensor_list = new JSONArray();

                for (Sensor sensor : sensors) {
                    JSONObject sensor_info = new JSONObject();

                    sensor_info.put("name", sensor.getName());
                    sensor_info.put("type", sensor.getType());
                    sensor_info.put("vendor", sensor.getVendor());
                    sensor_info.put("version", sensor.getVersion());
                    sensor_info.put("power", roundValue(sensor.getPower(), 4));
                    sensor_info.put("resolution", roundValue(sensor.getResolution(), 4));
                    sensor_info.put("range", roundValue(sensor.getMaximumRange(), 4));

                    sensor_list.put(sensor_info);
                }

                json.put("sensors", sensor_list);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
    // http://developer.android.com/reference/android/net/ConnectivityManager.html
    if (prefs.getBoolean("UseConn", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "conn");
            json.put("ts", ts);

            if (cm == null) {
                cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            }

            // TODO: add active/all preferences below UseConn
            if (prefs.getBoolean("UseConnActive", true)) {
                NetworkInfo net = cm.getActiveNetworkInfo();
                if (net != null) {
                    JSONObject net_data = new JSONObject();

                    net_data.put("type", net.getTypeName());
                    net_data.put("subtype", net.getSubtypeName());
                    net_data.put("connected", net.isConnected());
                    net_data.put("available", net.isAvailable());
                    net_data.put("roaming", net.isRoaming());
                    net_data.put("failover", net.isFailover());
                    if (net.getReason() != null)
                        net_data.put("reason", net.getReason());
                    if (net.getExtraInfo() != null)
                        net_data.put("extra", net.getExtraInfo());

                    json.put("conn_active", net_data);
                }
            }

            if (prefs.getBoolean("UseConnAll", false)) {
                NetworkInfo[] nets = cm.getAllNetworkInfo();
                if (nets != null) {
                    JSONArray net_list = new JSONArray();

                    for (NetworkInfo net : nets) {
                        JSONObject net_data = new JSONObject();

                        net_data.put("type", net.getTypeName());
                        net_data.put("subtype", net.getSubtypeName());
                        net_data.put("connected", net.isConnected());
                        net_data.put("available", net.isAvailable());
                        net_data.put("roaming", net.isRoaming());
                        net_data.put("failover", net.isFailover());
                        if (net.getReason() != null)
                            net_data.put("reason", net.getReason());
                        if (net.getExtraInfo() != null)
                            net_data.put("extra", net.getExtraInfo());

                        net_list.put(net_data);
                    }

                    json.put("conn_all", net_list);
                }
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    if (!PingServiceReceiver.completeWakefulIntent(intent)) {
        Log.w(tag, "completeWakefulIntent() failed. no active wake lock?");
    }
}

From source file:org.openhab.habdroid.ui.OpenHABStartupActivity.java

private void initPage() {

    if (!tryManualUrl()) {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null) {
            Log.i(TAG, "Network is connected");
            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
                    || activeNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                Log.i(TAG, "Network is WiFi or Ethernet");
                AsyncServiceResolver serviceResolver = new AsyncServiceResolver(this, openHABServiceType);
                if (!this.isFinishing())
                    progressDialog = ProgressDialog.show(OpenHABStartupActivity.this, "",
                            "Discovering openHAB. Please wait...", true);
                serviceResolver.start();
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                Log.i(TAG, "Network is Mobile (" + activeNetworkInfo.getSubtypeName() + ")");
                onAlternativeUrl();//from   w  ww.  j av  a 2 s . co  m
            } else {
                Log.i(TAG, "Network type (" + activeNetworkInfo.getTypeName() + ") is unsupported");
            }
        } else {
            Log.i(TAG, "Network is not available");
            Toast.makeText(getApplicationContext(), "@string/error_network_not_available", Toast.LENGTH_LONG)
                    .show();
        }
    }

}

From source file:fr.inria.ucn.collectors.NetworkStateCollector.java

/**
 * /*  w w w  . j a  v  a2 s.  c om*/
 * @param c
 * @param ts
 * @param change
 */
@SuppressWarnings("deprecation")
@SuppressLint({ "DefaultLocale", "NewApi" })
public void run(Context c, long ts, boolean change) {
    try {
        // current active interface (wifi or mobile) and config
        ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();

        JSONObject data = new JSONObject();
        data.put("on_network_state_change", change); // this collection run was triggered by network change
        data.put("is_connected", (ni != null && ni.isConnectedOrConnecting()));
        data.put("is_roaming", tm.isNetworkRoaming());

        // airplane mode ?
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            data.put("is_airplane_mode",
                    (Settings.System.getInt(c.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0));
        } else {
            data.put("is_airplane_mode",
                    (Settings.Global.getInt(c.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0));
        }

        if (ni != null) {
            JSONObject active = new JSONObject();
            active.put("type", ni.getType());
            active.put("subtype", ni.getSubtype());
            active.put("type_name", ni.getTypeName());
            active.put("subtype_name", ni.getSubtypeName());
            active.put("state", ni.getState().toString());
            active.put("detailed_state", ni.getDetailedState().toString());
            active.put("is_wifi", (ni.getType() == ConnectivityManager.TYPE_WIFI));
            data.put("active_network", active);

            if (ni.getType() == ConnectivityManager.TYPE_WIFI) {
                data.put("wifi_network", getWifi(c));
            }
        }

        // mobile network details
        data.put("mobile_network", getMobile(tm));

        // kernel network statistics
        data.put("netstat", getNetstat());

        // interfaces config
        Map<String, JSONObject> stats = networkStats();
        data.put("ifconfig", getIfconfig(stats));

        // double check interfaces
        data.put("ip_addr_show", getIpAddr(stats));

        Helpers.sendResultObj(c, "network_state", ts, data);

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json object", jex);
    }
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetListActivity.java

/**
 * This is called when activity is created. Initializes the state, performs network
 * state based selection for app initialization and starts the widget list
 *///from  w  w w .j  a  va2 s . c  o m
@Override
public void onCreate(Bundle savedInstanceState) {
    Log.d("OpenHABWidgetListActivity", "onCreate");
    // Set default values, false means do it one time during the very first launch
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    // Set non-persistant HABDroid version preference to current version from application package
    try {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("default_openhab_appversion",
                getPackageManager().getPackageInfo(getPackageName(), 0).versionName).commit();
    } catch (NameNotFoundException e1) {
        if (e1 != null)
            Log.d(TAG, e1.getMessage());
    }
    // Set the theme to one from preferences
    Util.setActivityTheme(this);
    // Fetch openHAB service type name from strings.xml
    openHABServiceType = getString(R.string.openhab_service_type);
    // Enable progress ring bar
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    setProgressBarIndeterminateVisibility(true);
    // Initialize crittercism reporting
    JSONObject crittercismConfig = new JSONObject();
    try {
        crittercismConfig.put("shouldCollectLogcat", true);
    } catch (JSONException e) {
        if (e.getMessage() != null)
            Log.e(TAG, e.getMessage());
        else
            Log.e(TAG, "Crittercism JSON exception");
    }
    Crittercism.init(getApplicationContext(), "5117659f59e1bd4ba9000004", crittercismConfig);
    // Initialize activity view
    super.onCreate(savedInstanceState);
    setContentView(R.layout.openhabwidgetlist);
    // Disable screen timeout if set in preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    if (settings.getBoolean("default_openhab_screentimeroff", false)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
    // Check if we got all needed permissions
    PackageManager pm = getPackageManager();
    if (!(pm.checkPermission(permission.CHANGE_WIFI_MULTICAST_STATE,
            getPackageName()) == PackageManager.PERMISSION_GRANTED)) {
        showAlertDialog(getString(R.string.erorr_no_wifi_mcast_permission));
        serviceDiscoveryEnabled = false;
    }
    if (!(pm.checkPermission(permission.ACCESS_WIFI_STATE,
            getPackageName()) == PackageManager.PERMISSION_GRANTED)) {
        showAlertDialog(getString(R.string.erorr_no_wifi_state_permission));
        serviceDiscoveryEnabled = false;
    }
    // Get username/password from preferences
    openHABUsername = settings.getString("default_openhab_username", null);
    openHABPassword = settings.getString("default_openhab_password", null);
    // Create new data source and adapter and set it to list view
    openHABWidgetDataSource = new OpenHABWidgetDataSource();
    openHABWidgetAdapter = new OpenHABWidgetAdapter(OpenHABWidgetListActivity.this,
            R.layout.openhabwidgetlist_genericitem, widgetList);
    getListView().setAdapter(openHABWidgetAdapter);
    // Set adapter parameters
    openHABWidgetAdapter.setOpenHABUsername(openHABUsername);
    openHABWidgetAdapter.setOpenHABPassword(openHABPassword);
    // Enable app logo as home button
    this.getActionBar().setHomeButtonEnabled(true);
    // Check if we have openHAB page url in saved instance state?
    if (savedInstanceState != null) {
        displayPageUrl = savedInstanceState.getString("displayPageUrl");
        openHABBaseUrl = savedInstanceState.getString("openHABBaseUrl");
        sitemapRootUrl = savedInstanceState.getString("sitemapRootUrl");
        openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl);
    }
    // Check if this is a launch from myself (drill down navigation)
    if (getIntent() != null) {
        if (getIntent().getAction() != null) {
            if (getIntent().getAction().equals("org.openhab.habdroid.ui.OpwnHABWidgetListActivity")) {
                displayPageUrl = getIntent().getExtras().getString("displayPageUrl");
                openHABBaseUrl = getIntent().getExtras().getString("openHABBaseUrl");
                sitemapRootUrl = getIntent().getExtras().getString("sitemapRootUrl");
                this.setTitle(getIntent().getExtras().getString("pageTitle"));
                openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl);
            }
        }
    }
    // If yes, then just go to it (means restore activity from it's saved state)
    if (displayPageUrl.length() > 0) {
        Log.d(TAG, "displayPageUrl = " + displayPageUrl);
        showPage(displayPageUrl, false);
        // If not means it is a clean start
    } else {
        if (getIntent() != null) {
            Log.i(TAG, "Launch intent = " + getIntent().getAction());
            // If this is a launch through NFC tag reading
            if (getIntent().getAction() != null) {
                if (getIntent().getAction().equals("android.nfc.action.NDEF_DISCOVERED")) {
                    // Save url which we got from NFC tag
                    nfcTagData = getIntent().getDataString();
                }
            }
        }
        // If we are in demo mode, ignore all settings and use demo url from strings
        if (settings.getBoolean("default_openhab_demomode", false)) {
            openHABBaseUrl = getString(R.string.openhab_demo_url);
            Log.i(TAG, "Demo mode, connecting to " + openHABBaseUrl);
            Toast.makeText(getApplicationContext(), getString(R.string.info_demo_mode), Toast.LENGTH_LONG)
                    .show();
            showTime();
        } else {
            openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_url", ""));
            // Check if we have a direct URL in preferences, if yes - use it
            if (openHABBaseUrl.length() > 0) {
                Log.i(TAG, "Connecting to configured URL = " + openHABBaseUrl);
                Toast.makeText(getApplicationContext(), getString(R.string.info_conn_url), Toast.LENGTH_SHORT)
                        .show();
                showTime();
            } else {
                // Get current network information
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                        Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                if (activeNetworkInfo != null) {
                    Log.i(TAG, "Network is connected");
                    // If network is mobile, try to use remote URL
                    if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE
                            || serviceDiscoveryEnabled == false) {
                        if (!serviceDiscoveryEnabled) {
                            Log.i(TAG, "openHAB discovery is disabled");
                        } else {
                            Log.i(TAG, "Network is Mobile (" + activeNetworkInfo.getSubtypeName() + ")");
                        }
                        openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_alturl", ""));
                        // If remote URL is configured
                        if (openHABBaseUrl.length() > 0) {
                            Toast.makeText(getApplicationContext(), getString(R.string.info_conn_rem_url),
                                    Toast.LENGTH_SHORT).show();
                            Log.i(TAG, "Connecting to remote URL " + openHABBaseUrl);
                            showTime();
                        } else {
                            Toast.makeText(getApplicationContext(), getString(R.string.error_no_url),
                                    Toast.LENGTH_LONG).show();
                        }
                        // If network is WiFi or Ethernet
                    }
                    if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
                            || activeNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                        Log.i(TAG, "Network is WiFi or Ethernet");
                        // Start service discovery
                        this.serviceResolver = new AsyncServiceResolver(this, openHABServiceType);
                        progressDialog = ProgressDialog.show(this, "", "Discovering openHAB. Please wait...",
                                true);
                        this.serviceResolver.start();
                        // We don't know how to handle this network type
                    } else {
                        Log.i(TAG, "Network type (" + activeNetworkInfo.getTypeName() + ") is unsupported");
                    }
                    // Network is not available
                } else {
                    Log.i(TAG, "Network is not available");
                    Toast.makeText(getApplicationContext(), getString(R.string.error_network_not_available),
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public String getCurrentAccessPoint() {

    ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info == null) {
        return null;
    }/* w w w  . java  2  s.co m*/
    String apName = info.getTypeName() + "_" + info.getSubtypeName();
    if (info.getExtraInfo() != null) {
        apName += "_" + info.getExtraInfo();
    }
    return apName;
}