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:org.pidome.client.phone.services.SystemService.java

private void setHome() {
    if (prefs != null) {
        if (prefs.getBoolPreference("wifiConnectHomeEnabled", false)) {
            ConnectivityManager connManager = (ConnectivityManager) getSystemService(
                    Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
                if (connectionInfo != null) {
                    String SSID = connectionInfo.getSSID();
                    String BSSID = connectionInfo.getBSSID();
                    if (SSID != null && BSSID != null) {
                        if (SSID.equals(prefs.getStringPreference("wifiConnectSSID",
                                java.util.UUID.randomUUID().toString()))
                                && BSSID.equals(prefs.getStringPreference("wifiConnectBSSID",
                                        java.util.UUID.randomUUID().toString()))) {
                            if (this.system != null) {
                                try {
                                    system.getClient().getEntities().getPresenceService().setPresence(1);
                                } catch (EntityNotAvailableException ex) {
                                    Logger.getLogger(SystemService.class.getName()).log(Level.SEVERE, null, ex);
                                }/*from  www  . j  av a2  s .  c om*/
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:eu.intermodalics.tango_ros_streamer.RunningActivity.java

/**
 * This function initializes the tango ros node with RosJava interface.
 *//*from  w  w w.  j  a v a 2  s.  com*/
private void initAndStartRosJavaNode() {
    if (mRunLocalMaster) {
        this.nodeMainExecutorService.startMaster(/*isPrivate*/ false);
        mMasterUri = this.nodeMainExecutorService.getMasterUri().toString();
        // The URI returned by getMasterUri is correct but looks 'weird',
        // e.g. 'http://android-c90553518bc67cf5:1131'.
        // Instead of showing this to the user, we show the IP address of the device,
        // which is also correct and less confusing.
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        String deviceIP = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
        mUriTextView = (TextView) findViewById(R.id.master_uri);
        mUriTextView.setText("http://" + deviceIP + ":11311");
    }
    if (mMasterUri != null) {
        URI masterUri;
        try {
            masterUri = URI.create(mMasterUri);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Wrong URI: " + e.getMessage());
            return;
        }
        this.nodeMainExecutorService.setMasterUri(masterUri);
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                RunningActivity.this.init(nodeMainExecutorService);
                return null;
            }
        }.execute();
    } else {
        Log.e(TAG, "Master URI is null");
    }
}

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

@Override
public void onStart() {
    super.onStart();

    // Print version number
    Context mContext = SpydroidApplication.getContext();
    try {/*from   w  ww .jav a2 s  .  co m*/
        //mVersion.setText("v"+mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0 ).versionName);
        mVersion.setText("v0.1");
    } catch (Exception e) {
        mVersion.setText("v???");
    }

    displayIpAddress();

    WifiManager wifiManager = (WifiManager) SpydroidApplication.getContext()
            .getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo();
    int i = info.getIpAddress();
    final String ip = String.format(Locale.ENGLISH, "%d.%d.%d.%d", i & 0xff, i >> 8 & 0xff, i >> 16 & 0xff,
            i >> 24 & 0xff);

    final String socketUrl = "http://192.168.1.10:3000/socket.io/1/";
    final Properties handshakeHeaders = new Properties();
    handshakeHeaders.setProperty("X-COLLAB-MEETINGID", "5161e2d4e83131372e000001");
    handshakeHeaders.setProperty("X-COLLAB-CONNECTION", ip + ":8086");

    mStartButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Log.i(TAG, "Attempting to connect to " + socketUrl);
                socket = new SocketIO(socketUrl, handshakeHeaders);

            } catch (MalformedURLException e) {
                Log.e(TAG, e.getMessage());
            }

            socket.connect(new IOCallback() {
                @Override
                public void onMessage(String data, IOAcknowledge ack) {
                    Log.i(TAG, data);
                    System.out.println("Server said: " + data);
                }

                @Override
                public void onError(SocketIOException socketIOException) {
                    System.out.println("an Error occured");
                    socketIOException.printStackTrace();
                    Log.e(TAG, socketIOException.getLocalizedMessage());

                }

                @Override
                public void onDisconnect() {
                    System.out.println("Connection terminated.");
                }

                @Override
                public void onConnect() {
                    System.out.println("Connection established");
                }

                @Override
                public void on(String event, IOAcknowledge ack, Object... args) {
                    System.out.println("Server triggered event '" + event + "'");
                }

                @Override
                public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
                    Log.i(TAG, arg0.toString());
                }
            });
            /*
            //final String socketUrl = "http://192.168.1.10:3000/.io/1/?meeting=5161e2d4e83131372e000001&connection=" + ip + ":8086";
            final String socketUrl = "http://192.168.1.10:3000/socket.io/1/";
            List<BasicNameValuePair> extraHeaders = Arrays.asList(
                   new BasicNameValuePair("X-COLLAB-MEETINGID", "5161e2d4e83131372e000001"),
                   new BasicNameValuePair("X-COLLAB-CONNECTION", ip + ":8086" )
               );
            socket = new SocketIOClient(URI.create(socketUrl), new SocketIOClient.Handler() {
                @Override
                public void onConnect() {
            Log.d(TAG, "Connected!");
                }
                    
                @Override
                public void on(String event, JSONArray arguments) {
            Log.d(TAG, String.format("Got event %s: %s", event, arguments.toString()));
                }
                    
                @Override
                public void onJSON(JSONObject json) {
            Log.d(TAG, String.format("Got JSON Object: %s", json.toString()));
                }
                    
                @Override
                public void onMessage(String message) {
            Log.d(TAG, String.format("Got message: %s", message));
                }
                    
                @Override
                public void onDisconnect(int code, String reason) {
            Log.d(TAG, String.format("Disconnected! Code: %d Reason: %s", code, reason));
                }
                    
                @Override
                public void onError(Exception error) {
            Log.e(TAG, "Error!", error);
                }
            }, extraHeaders);
                    
                    
            socket.connect();
            */
        }
    });

    mStopButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            socket.emit("kill");
            socket.disconnect();
            socket = null;
        }
    });
}

From source file:net.helff.wificonnector.WifiConnectivityService.java

protected void checkWifi() throws ConnectionWorkflowException {
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager != null ? wifiManager.getConnectionInfo() : null;
    if (!TELEFONICA_SSID.equals(this.normalizeSSID(wifiInfo))) {
        // post error
        publishProgress(getString(R.string.not_connected), getString(R.string.not_connected_detail),
                STATUS_NOT_CONNECTED);/*from   www . j a va  2s  . c  o m*/
        throw new ConnectionWorkflowException("No connection to TelefonicaPublic");
    }
}

From source file:org.teleal.cling.android.browser.MainActivity.java

public void switchToDeviceList() {
    setListAdapter(deviceListAdapter);//from ww  w .  j  ava 2  s. c  o  m

    /*
     * Executes when the user (long) clicks on a device:
     */
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            DeviceDisplay clickedDisplay = deviceListAdapter.getItem(position);
            if (clickedDisplay != null) {
                // ... clickedDisplay.getDevice();
                Service service = clickedDisplay.getDevice().findService(new UDAServiceId("SwitchPower"));
                if (service != null) {
                    Action getStatusAction = service.getAction("GetTarget");
                    ActionInvocation getStatusInvocation = new ActionInvocation(getStatusAction);

                    new ActionCallback.Default(getStatusInvocation, upnpService.getControlPoint()).run();

                    boolean value = ((Boolean) getStatusInvocation.getOutput("RetTargetValue").getValue())
                            .booleanValue();

                    Action setTargetAction = service.getAction("SetTarget");
                    ActionInvocation setTargetInvocation = new ActionInvocation(setTargetAction);
                    setTargetInvocation.setInput("NewTargetValue", !value);

                    ActionCallback setTargetCallback = new ActionCallback(setTargetInvocation) {

                        @Override
                        public void success(ActionInvocation invocation) {
                            ActionArgumentValue[] output = invocation.getOutput();
                            // assertEquals(output.length, 0);
                        }

                        @Override
                        public void failure(ActionInvocation invocation, UpnpResponse operation,
                                String defaultMsg) {
                            System.err.println(defaultMsg);
                        }
                    };

                    upnpService.getControlPoint().execute(setTargetCallback);
                }

                Service service2 = clickedDisplay.getDevice().findService(new UDAServiceId("ContentDirectory"));
                if (service2 != null) {
                    DeviceIdentity identity = clickedDisplay.getDevice().getIdentity();

                    WifiManager mng = (WifiManager) getSystemService(WIFI_SERVICE);
                    WifiInfo info = mng.getConnectionInfo();
                    String mac = info.getMacAddress();

                    SendPost2 sendPost = new SendPost2(MainActivity.this);
                    sendPost.execute(mac.toString());

                    switchToContentList(identity);
                }
            }
        }
    });

}

From source file:com.ifoer.util.NetPOSPrinter.java

public int printPic(Bitmap bmp) {
    WifiManager wifi_service = (WifiManager) this.mContext.getSystemService("wifi");
    DhcpInfo dhcpinfo = wifi_service.getDhcpInfo();
    WifiInfo wifi_info = wifi_service.getConnectionInfo();
    if (wifi_info != null && wifi_info.getSSID() != null && !wifi_info.getSSID().startsWith("X-431PRINTER")) {
        return PRINT_NOT_CONNECT;
    }//ww w.ja v  a 2s.com
    this.serverAddress = dhcpinfo.serverAddress;
    try {
        this.wifiSocket = new Socket(Formatter.formatIpAddress(this.serverAddress), PRINT_PORT);
        this.dos = new DataOutputStream(this.wifiSocket.getOutputStream());
        this.in = new DataInputStream(this.wifiSocket.getInputStream());
    } catch (UnknownHostException e1) {
        e1.printStackTrace();
    } catch (IOException e12) {
        e12.printStackTrace();
    }
    if (this.dos == null || this.in == null) {
        return PRINT_NOT_CONNECT;
    }
    byte[] data = new byte[3];
    data[0] = (byte) 27;
    data[ERROR_PRINT_JAM] = (byte) 51;
    try {
        this.dos.write(data, 0, data.length);
        data[0] = (byte) 0;
        data[ERROR_PRINT_JAM] = (byte) 0;
        data[ERROR_PRINT_WILL_NO_PAPER] = (byte) 0;
    } catch (IOException e122) {
        e122.printStackTrace();
    }
    byte[] escj = new byte[3];
    escj[0] = (byte) 27;
    escj[ERROR_PRINT_JAM] = (byte) 74;
    int i = 3;
    byte[] esccheck = new byte[] { (byte) 29, (byte) 114, (byte) 73 };
    byte[] escBmp = new byte[5];
    escBmp[0] = (byte) 27;
    escBmp[ERROR_PRINT_JAM] = (byte) 42;
    escBmp[ERROR_PRINT_WILL_NO_PAPER] = SmileConstants.TOKEN_LITERAL_NULL;
    escBmp[3] = (byte) (bmp.getWidth() % KEYRecord.OWNER_ZONE);
    escBmp[ERROR_PRINT_NO_PAPER] = (byte) (bmp.getWidth() / KEYRecord.OWNER_ZONE);
    for (int i2 = 0; i2 < (bmp.getHeight() / 24) + ERROR_PRINT_JAM; i2 += ERROR_PRINT_JAM) {
        try {
            this.dos.write(escBmp, 0, escBmp.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int j = 0; j < bmp.getWidth(); j += ERROR_PRINT_JAM) {
            for (int k = 0; k < 24; k += ERROR_PRINT_JAM) {
                if ((i2 * 24) + k < bmp.getHeight()) {
                    if (Color.red(bmp.getPixel(j, (i2 * 24) + k)) == 0) {
                        int i3 = k / ERROR_PRINT_ACTUATOR_FAULT;
                        data[i3] = (byte) (data[i3]
                                + ((byte) (ERROR_PRINT_HEAD_OVERHEATING >> (k % ERROR_PRINT_ACTUATOR_FAULT))));
                    }
                }
            }
            try {
                this.dos.write(data, 0, data.length);
                data[0] = (byte) 0;
                data[ERROR_PRINT_JAM] = (byte) 0;
                data[ERROR_PRINT_WILL_NO_PAPER] = (byte) 0;
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        try {
            if (i2 % 10 == 0) {
                this.dos.write(esccheck);
                if (this.in.readByte() == null) {
                    this.dos.write(escj, 0, escj.length);
                }
            } else {
                this.dos.write(escj, 0, escj.length);
            }
        } catch (IOException e22) {
            e22.printStackTrace();
        }
    }
    i = 3;
    byte[] escf = new byte[] { (byte) 29, (byte) 122, (byte) 49 };
    i = 3;
    byte[] esck = new byte[] { (byte) 27, (byte) 74, (byte) 64 };
    try {
        this.dos.write(escf);
        this.dos.write(esck);
        this.result = this.in.readByte();
        try {
            this.dos.close();
            this.in.close();
        } catch (IOException e222) {
            e222.printStackTrace();
        }
        return this.result;
    } catch (IOException e3) {
        return PRINT_NOT_CONNECT;
    }
}

From source file:riddimon.android.asianetautologin.CredentialActivity.java

private void refreshNetworkSpinnerIfNecessary() {
    if (mSsids != null && mSsids.size() != 0)
        return;//from  ww  w  .  ja v a  2 s  .  co  m
    //get wifi networks
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<WifiConfiguration> lwc = wm.getConfiguredNetworks();
    WifiInfo wi = wm.getConnectionInfo();
    String wssid = null;
    if (wi != null && wm.isWifiEnabled()) {
        String ssid = wi.getSSID();
        if (!TextUtils.isEmpty(ssid)) {
            wssid = ssid.replace("\"", "");
        }
    }

    mSsids = new ArrayList<String>();
    int selection = 0;
    if (lwc != null) {
        int i = -1;
        for (WifiConfiguration wc : lwc) {
            i++;
            String ssid = TextUtils.isEmpty(wc.SSID) ? "" : wc.SSID.replace("\"", "");
            mSsids.add(ssid);
            if (!TextUtils.isEmpty(wssid) && ssid.equals(wssid)) {
                selection = i;
            }
        }
    }

    mSsid.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mSsids));
    if (mSsids != null && mSsids.size() > 0) {
        mSsid.setSelection(selection);
    }
}

From source file:net.olejon.spotcommander.AddComputerActivity.java

private void scanNetwork() {
    if (mNetworkScanTask != null && mNetworkScanTask.getStatus() == AsyncTask.Status.RUNNING) {
        mNetworkScanTask.cancel(true);/*from   w  w  w  .jav a2s  .c  o  m*/
    } else {
        final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

        if (wifiManager.isWifiEnabled()) {
            final WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            final int wifiIpAddress = wifiInfo.getIpAddress();

            final String wifiSubnet = String.format("%d.%d.%d", (wifiIpAddress & 0xff),
                    (wifiIpAddress >> 8 & 0xff), (wifiIpAddress >> 16 & 0xff));

            if (wifiSubnet.equals("0.0.0")) {
                mTools.showToast(getString(R.string.add_computer_wifi_not_connected), 0);
            } else {
                mNetworkScanTask = new NetworkScanTask();
                mNetworkScanTask.execute(wifiSubnet);
            }
        } else {
            mTools.showToast(getString(R.string.add_computer_wifi_not_connected), 0);
        }
    }
}

From source file:uk.ac.horizon.ubihelper.service.Service.java

public String getDeviceId() {
    WifiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE);
    if (wifi != null) {
        WifiInfo wi = wifi.getConnectionInfo();
        if (wi != null) {
            return wi.getMacAddress();
        }//from   www .  j  ava 2  s .  c om
    }
    Log.w(TAG, "Could not get device ID");
    return "UNKNOWNID";
}

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

private JSONObject getWifi(Context c) throws JSONException {
    WifiManager wm = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wi = wm.getConnectionInfo();

    // start a wifi AP scan
    Helpers.acquireWifiLock(c);/*  w ww  . j a  v  a2 s.  co m*/
    IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    c.registerReceiver(this, filter);
    wm.startScan();

    JSONObject o = new JSONObject();
    o.put("link_speed", wi.getLinkSpeed());
    o.put("link_speed_units", WifiInfo.LINK_SPEED_UNITS);
    o.put("signal_level", WifiManager.calculateSignalLevel(wi.getRssi(), 100));
    o.put("rssi", wi.getRssi());
    o.put("bssid", wi.getBSSID());
    o.put("ssid", wi.getSSID().replaceAll("\"", ""));
    o.put("mac", wi.getMacAddress());

    int ip = wi.getIpAddress();
    String ipstr = String.format(Locale.US, "%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff),
            (ip >> 24 & 0xff));
    o.put("ip", ipstr);

    return o;
}