Example usage for android.net.wifi WifiManager getConnectionInfo

List of usage examples for android.net.wifi WifiManager getConnectionInfo

Introduction

In this page you can find the example usage for android.net.wifi WifiManager getConnectionInfo.

Prototype

public WifiInfo getConnectionInfo() 

Source Link

Document

Return dynamic information about the current Wi-Fi connection, if any is active.

Usage

From source file:com.mstar.tv.tvplayer.philips.option.OptionFirstFragment.java

private boolean isWifiConnected() {
    WifiManager wifiManager = getWifiManager();
    // wifi is disabled
    if (!wifiManager.isWifiEnabled()) {
        return false;
    }//from   ww w.ja v  a2s  . c  o m

    // wifi have not connected
    WifiInfo info = wifiManager.getConnectionInfo();
    if (info == null || info.getSSID() == null || info.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID) {
        return false;
    }

    return true;
}

From source file:net.majorkernelpanic.spydroid.ui.HandsetFragment.java

public void displayIpAddress() {
    WifiManager wifiManager = (WifiManager) SpydroidApplication.getContext()
            .getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo();
    String ipaddress = null;/*from  w ww.j a  v  a 2s.c  om*/
    Log.d("SpydroidActivity", "getNetworkId " + info.getNetworkId());
    if (info != null && info.getNetworkId() > -1) {
        int i = info.getIpAddress();
        String ip = String.format(Locale.ENGLISH, "%d.%d.%d.%d", i & 0xff, i >> 8 & 0xff, i >> 16 & 0xff,
                i >> 24 & 0xff);
        mLine1.setText("http://");
        mLine1.append(ip);
        mLine1.append(":" + SpydroidApplication.sHttpPort);
        mLine2.setText("rtsp://");
        mLine2.append(ip);
        mLine2.append(":" + SpydroidApplication.sRtspPort);
        streamingState(0);
    } else if ((ipaddress = Utilities.getLocalIpAddress(true)) != null) {
        mLine1.setText("http://");
        mLine1.append(ipaddress);
        mLine1.append(":" + SpydroidApplication.sHttpPort);
        mLine2.setText("rtsp://");
        mLine2.append(ipaddress);
        mLine2.append(":" + SpydroidApplication.sRtspPort);
        streamingState(0);
    } else {
        mLine1.setText("HTTP://xxx.xxx.xxx.xxx:" + SpydroidApplication.sHttpPort);
        mLine2.setText("RTSP://xxx.xxx.xxx.xxx:" + SpydroidApplication.sHttpPort);
        streamingState(2);
    }
}

From source file:net.micode.fileexplorer.ServerControlActivity.java

/**
 * This will be called by the static UiUpdater whenever the service has
 * changed state in a way that requires us to update our UI. We can't use
 * any myLog.l() calls in this function, because that will trigger an
 * endless loop of UI updates./*from  w  w  w  .j a v a  2 s  .  c  o  m*/
 */
public void updateUi() {
    myLog.l(Log.DEBUG, "Updating UI", true);

    WifiManager wifiMgr = (WifiManager) mActivity.getSystemService(Context.WIFI_SERVICE);
    int wifiState = wifiMgr.getWifiState();
    WifiInfo info = wifiMgr.getConnectionInfo();
    String wifiId = info != null ? info.getSSID() : null;
    boolean isWifiReady = FTPServerService.isWifiEnabled();

    setText(R.id.wifi_state, isWifiReady ? wifiId : getString(R.string.no_wifi_hint));
    ImageView wifiImg = (ImageView) mRootView.findViewById(R.id.wifi_state_image);
    wifiImg.setImageResource(isWifiReady ? R.drawable.wifi_state4 : R.drawable.wifi_state0);

    boolean running = FTPServerService.isRunning();
    if (running) {
        myLog.l(Log.DEBUG, "updateUi: server is running", true);
        // Put correct text in start/stop button
        // Fill in wifi status and address
        InetAddress address = FTPServerService.getWifiIp();
        if (address != null) {
            String port = ":" + FTPServerService.getPort();
            ipText.setText(
                    "ftp://" + address.getHostAddress() + (FTPServerService.getPort() == 21 ? "" : port));

        } else {
            // could not get IP address, stop the service
            Context context = mActivity.getApplicationContext();
            Intent intent = new Intent(context, FTPServerService.class);
            context.stopService(intent);
            ipText.setText("");
        }
    }

    startStopButton.setEnabled(isWifiReady);
    TextView startStopButtonText = (TextView) mRootView.findViewById(R.id.start_stop_button_text);
    if (isWifiReady) {
        startStopButtonText.setText(running ? R.string.stop_server : R.string.start_server);
        startStopButtonText.setCompoundDrawablesWithIntrinsicBounds(
                running ? R.drawable.disconnect : R.drawable.connect, 0, 0, 0);
        startStopButtonText.setTextColor(running ? getResources().getColor(R.color.remote_disconnect_text)
                : getResources().getColor(R.color.remote_connect_text));
    } else {
        if (FTPServerService.isRunning()) {
            Context context = mActivity.getApplicationContext();
            Intent intent = new Intent(context, FTPServerService.class);
            context.stopService(intent);
        }

        startStopButtonText.setText(R.string.no_wifi);
        startStopButtonText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        startStopButtonText.setTextColor(Color.GRAY);
    }

    ipText.setVisibility(running ? View.VISIBLE : View.INVISIBLE);
    instructionText.setVisibility(running ? View.VISIBLE : View.GONE);
    instructionTextPre.setVisibility(running ? View.GONE : View.VISIBLE);
}

From source file:org.pidome.client.phone.services.SystemService.java

/**
 * Generate an unique id for this device.
 * @param context/*from w  w  w . j av  a 2  s . c  om*/
 * @return 
 */
private String generateDeviceId(Context context) {
    final String macAddr, androidId;
    WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInf = wifiMan.getConnectionInfo();
    macAddr = wifiInf.getMacAddress();
    androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(),
            android.provider.Settings.Secure.ANDROID_ID);
    UUID deviceUuid;
    try {
        deviceUuid = new UUID(androidId.hashCode(), macAddr.hashCode());
    } catch (NullPointerException ex) {
        deviceUuid = new UUID(androidId.hashCode(), androidId.hashCode());
    }
    return deviceUuid.toString();
}

From source file:ch.ethz.coss.nervousnet.vm.sensors.ConnectivitySensor.java

public void runConnectivitySensor() {
    Log.d(LOG_TAG, "Inside runConnectivitySensor");
    if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(context,
            android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;// w  w w  . jav  a 2 s  . c  om
    }
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    int networkType = -1;
    boolean isRoaming = false;
    if (isConnected) {
        networkType = activeNetwork.getType();
        isRoaming = activeNetwork.isRoaming();
    }

    String wifiHashId = "";
    int wifiStrength = Integer.MIN_VALUE;

    if (networkType == ConnectivityManager.TYPE_WIFI) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wi = wm.getConnectionInfo();
        StringBuilder wifiInfoBuilder = new StringBuilder();
        wifiInfoBuilder.append(wi.getBSSID());
        wifiInfoBuilder.append(wi.getSSID());
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(wifiInfoBuilder.toString().getBytes());
            wifiHashId = new String(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
        }
        wifiStrength = wi.getRssi();
    }

    byte[] cdmaHashId = new byte[32];
    byte[] lteHashId = new byte[32];
    byte[] gsmHashId = new byte[32];
    byte[] wcdmaHashId = new byte[32];

    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    List<CellInfo> cis = tm.getAllCellInfo();
    if (cis != null) {
        // New method
        for (CellInfo ci : cis) {
            if (ci.isRegistered()) {
                if (ci instanceof CellInfoCdma) {
                    CellInfoCdma cic = (CellInfoCdma) ci;
                    cdmaHashId = generateMobileDigestId(cic.getCellIdentity().getSystemId(),
                            cic.getCellIdentity().getNetworkId(), cic.getCellIdentity().getBasestationId());
                }
                if (ci instanceof CellInfoGsm) {
                    CellInfoGsm cic = (CellInfoGsm) ci;
                    gsmHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(),
                            cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCid());
                }
                if (ci instanceof CellInfoLte) {
                    CellInfoLte cic = (CellInfoLte) ci;
                    lteHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(),
                            cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCi());
                }
                if (ci instanceof CellInfoWcdma) {
                    CellInfoWcdma cic = (CellInfoWcdma) ci;
                    wcdmaHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(),
                            cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCid());
                }
            }
        }
    } else {
        // Legacy method
        CellLocation cl = tm.getCellLocation();
        if (cl instanceof CdmaCellLocation) {
            CdmaCellLocation cic = (CdmaCellLocation) cl;
            cdmaHashId = generateMobileDigestId(cic.getSystemId(), cic.getNetworkId(), cic.getBaseStationId());
        }
        if (cl instanceof GsmCellLocation) {
            GsmCellLocation cic = (GsmCellLocation) cl;
            gsmHashId = generateMobileDigestId(cic.getLac(), 0, cic.getCid());
        }
    }

    StringBuilder mobileHashBuilder = new StringBuilder();
    mobileHashBuilder.append(new String(cdmaHashId));
    mobileHashBuilder.append(new String(lteHashId));
    mobileHashBuilder.append(new String(gsmHashId));
    mobileHashBuilder.append(new String(wcdmaHashId));

    dataReady(new ConnectivityReading(System.currentTimeMillis(), isConnected, networkType, isRoaming,
            wifiHashId, wifiStrength, mobileHashBuilder.toString()));

}

From source file:devbox.com.br.minercompanion.ProfileActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);


    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo.isConnected()) {
        final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) {
            //if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) {
            routerName = connectionInfo.getSSID();
        }/*from  w  ww.  jav  a  2  s.  co  m*/
    }

    sensorCounter = new SensorCounter(3000, 3000);
    sensorCounter.start();

    Intent intent = getIntent();

    if(intent != null) {
        matricula = intent.getStringExtra("MATRICULA");

        TextView textView = (TextView) findViewById(R.id.textView);

        textView.setText("Matrcula: " + matricula);

        sensors = new Sensors(matricula, routerName.replace("\"",""));
    }

    /* Get a SensorManager instance */
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    ListView listView = (ListView) findViewById(R.id.listView);
    profileListAdapter = new ProfileListAdapter(this, strings);
    listView.setAdapter(profileListAdapter);

    profileListAdapter.addItem("Conectado ao servidor!");
}

From source file:tv.matchstick.demo.flingpic.FlingPicActivity.java

private void startWetServer(int port) {
    try {/*from  www.  ja v a 2s  . co  m*/
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        mIpAddress = intToIp(wifiInfo.getIpAddress());

        if (wifiInfo.getSupplicantState() != SupplicantState.COMPLETED) {
            new AlertDialog.Builder(this).setTitle("Error")
                    .setMessage("Please connect to a WIFI-network for starting the webserver.")
                    .setPositiveButton("OK", null).show();
            throw new Exception("Please connect to a WIFI-network.");
        }

        Log.e(TAG, "Starting server " + mIpAddress + ":" + port + ".");

        List<File> rootDirs = new ArrayList<File>();
        boolean quiet = false;
        Map<String, String> options = new HashMap<String, String>();
        rootDirs.add(new File(mRootDir).getAbsoluteFile());

        // mNanoHTTPD
        try {
            mNanoHTTPD = new SimpleWebServer(mIpAddress, port, rootDirs, quiet);
            mNanoHTTPD.start();
        } catch (IOException ioe) {
            Log.e(TAG, "Couldn't start server:\n" + ioe);
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}

From source file:com.sitewhere.android.example.MainActivity.java

private Map<String, String> buildRegistrationMetadata() {
    Map<String, String> metadata = new HashMap<>();

    WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
    String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

    String reqString = Build.MANUFACTURER + " " + Build.MODEL + " " + Build.VERSION.RELEASE + " "
            + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName();

    metadata.put("ipaddress", ip);
    metadata.put("android.os.version", Build.VERSION.BASE_OS);
    metadata.put("android.os.description", reqString);

    return metadata;
}

From source file:com.odo.kcl.mobileminer.miner.MinerService.java

private void connectivityChanged() {
    String name = "None";
    ConnectivityManager manager = (ConnectivityManager) getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = manager.getActiveNetworkInfo();
    if (netInfo != null) {
        if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
            switch (netInfo.getType()) {
            case ConnectivityManager.TYPE_WIFI:
                wifiData = true;//from  ww  w  . j  a  v  a  2s.co m
                mobileData = false;
                if (!updating)
                    startUpdating();
                WifiManager wifiMgr = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
                name = wifiInfo.getSSID();
                if (!networkName.equals(name)) {
                    wirelessData = new WifiData(wifiInfo);
                    MinerData helper = new MinerData(context);
                    helper.putWifiNetwork(helper.getWritableDatabase(), wirelessData, new Date());
                    helper.close();
                    networkName = name;
                    networkBroadcast();
                }
                startScan(); // Always scan when we've got WIFI.
                //Log.i("MinerService","CONNECTED: WIFI");
                break;
            case ConnectivityManager.TYPE_MOBILE:
                wifiData = false;
                mobileData = true;
                if ("goldfish".equals(Build.HARDWARE)) {
                    if (!updating)
                        startUpdating();
                } else {
                    updating = false;
                }

                // https://code.google.com/p/android/issues/detail?id=24227
                //String name; Cursor c;
                //c = this.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"), null, null, null, null);
                //name = c.getString(c.getColumnIndex("name"));
                TelephonyManager telephonyManager = ((TelephonyManager) this
                        .getSystemService(Context.TELEPHONY_SERVICE));
                name = telephonyManager.getNetworkOperatorName();
                if (!networkName.equals(name)) {
                    MinerData helper = new MinerData(context);
                    helper.putMobileNetwork(helper.getWritableDatabase(), telephonyManager, new Date());
                    helper.close();
                    networkName = name;
                    networkBroadcast();
                }
                //startScan();
                //Log.i("MinerService","CONNECTED MOBILE: "+name);
                break;
            default:
                //Log.i("MinerService",netInfo.getTypeName());
                break;
            }
        } else {
            scanning = false;
        }
    } else {
        scanning = false;
        networkName = "null";
    }

}

From source file:com.melchor629.musicote.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    // Set the user interface layout for this Activity
    // The layout file is defined in the project res/layout/main.xml file
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/* w  w  w  .  j a v a 2  s.  c o m*/
    appContext = getApplicationContext();

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.mainLayout);
    swipeRefreshLayout.setOnRefreshListener(this);
    swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimaryDark,
            R.color.colorGrey600);
    final ListView list = (ListView) findViewById(android.R.id.list);
    list.setOnScrollListener(new ListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            boolean enable = false;
            if (list != null && list.getChildCount() > 0) {
                // check if the first item of the list is visible
                boolean firstItemVisible = list.getFirstVisiblePosition() == 0;
                // check if the top of the first item is visible
                boolean topOfFirstItemVisible = list.getChildAt(0).getTop() == 0;
                // enabling or disabling the refresh layout
                enable = firstItemVisible && topOfFirstItemVisible;
            }
            swipeRefreshLayout.setEnabled(enable);
        }
    });
    getActionBar().setIcon(R.drawable.ic_launcher);
    getActionBar().setDisplayUseLogoEnabled(true);

    // La app prueba en busca de la direccin correcta
    WifiManager mw = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wi = mw.getConnectionInfo();
    String SSID = wi.getSSID();
    Log.i("MainActivity", "Wifi conectado: " + SSID + " " + (SSID != null ? SSID.equals("Madrigal") : ""));
    if (SSID == null) {
        SSID = "";
        Toast.makeText(this, getString(R.string.no_wifi), Toast.LENGTH_LONG).show();
    }
    if (SSID.equals("Madrigal") || SSID.contains("Madrigal")
            || System.getProperty("os.version").equals("3.4.67+")) {
        MainActivity.HOST = "192.168.1.133";
    } else {
        MainActivity.HOST = "reinoslokos.no-ip.org";
    }
    Log.i("MainActivity", "HOST: " + HOST);

    //Deletes the notification if remains (BUG)
    NotificationManager mn = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Reproductor.a == -1)
        mn.cancel(1);
    mn.cancel(3);

    //Revisa la base de datos
    DB mDbHelper = new DB(getBaseContext());
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    //Actualizacin de la lista
    if (mDbHelper.isNecesaryUpgrade(db) && Utils.HostTest(HOST) == 200)
        async();
    else
        cursordb(db);

    db.close();
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}