Example usage for android.net.wifi WifiInfo getIpAddress

List of usage examples for android.net.wifi WifiInfo getIpAddress

Introduction

In this page you can find the example usage for android.net.wifi WifiInfo getIpAddress.

Prototype

public int getIpAddress() 

Source Link

Usage

From source file:com.castoffline.castActivity.CastMedia.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    actionBar = getSupportActionBar();//from   w  w w . j a v  a  2 s .c  om
    setContentView(R.layout.castmedia);
    mediatype = this.getIntent().getType();
    extras = this.getIntent();

    //Get the ip of the device running NanoHTTPD server
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int ipAddress = wifiInfo.getIpAddress();
    ipdevice = String.format("http://%d.%d.%d.%d:8080", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
            (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));

    // start the webserver
    mediaserver = new webserver();
    try {
        mediaserver.start();
    } catch (IOException ioe) {
        Log.d("Httpd", "The server could not start.");
    }

    //The application needs to obtain an instance of the MediaRouter and needs to hold onto that instance for the lifetime of the sender application
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
    //The MediaRouter needs to filter discovery for Cast devices that can launch the receiver application associated with the sender app. For that a MediaRouteSelector is created by calling MediaRouteSelector.Builder
    mMediaRouteSelector = new MediaRouteSelector.Builder()
            .addControlCategory(CastMediaControlIntent.categoryForCast(getString(R.string.app_id))).build();
    // create an instance of MediaRouterCallback
    mMediaRouterCallback = new MyMediaRouterCallback();
    mediaplay();
}

From source file:org.androidpn.client.NotificationReceiver.java

private void onAdb(String notificationMessage) {
    // TODO Auto-generated method stub
    String adb01 = "setprop service.adb.tcp.port 5555";
    String adb02 = "stop adbd";
    String adb03 = "start adbd";
    String[] cmd01 = new String[] { "su", adb01 };
    String[] cmd02 = new String[] { "su", adb02 };
    String[] cmd03 = new String[] { "su", adb03 };
    try {/* w w w  .  jav a  2  s .co  m*/
        CMDUtil.execShellCMD(cmd01, 3);
        CMDUtil.execShellCMD(cmd02, 3);
        CMDUtil.execShellCMD(cmd03, 3);
        new Thread() {
            public void run() {
                String registerIp = context.getSharedPreferences(ConfigSP.SP_reseach, Context.MODE_PRIVATE)
                        .getString(ConfigSP.SP_reseach_ip, "");
                String serverIp = "http://" + registerIp;
                strImsi = context.getSharedPreferences(ConfigSP.SP_reseach, Context.MODE_PRIVATE)
                        .getString(ConfigSP.SP_reseach_Imsi, "");
                WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                strIp = intToIp(ipAddress);
                NameValuePair pairImsi = new BasicNameValuePair("strImsi", strImsi); // Imsi
                NameValuePair pairIp = new BasicNameValuePair("strIp", strIp);// ip
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                paramList.add(pairImsi);
                paramList.add(pairIp);

                String url = serverIp + ":8080/ResearchProject/sendcasemanager/sendstate";
                NetUtil.getInstance().httpUpload(context, url, paramList);
            };
        }.start();
    } catch (Exception exception) {
        exception.printStackTrace();
    } catch (Error error) {
        error.printStackTrace();
    }

}

From source file:cn.apputest.ctria.section2.Lucha2Activity.java

public String getLocalIPAddress() {
    // ?wifi?//from w  w w .ja v a2  s  .co  m
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    // wifi??
    if (!wifiManager.isWifiEnabled()) {
        String ip = getLocalIpAddressGPRS();
        return ip;
    } else {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = intToIp(ipAddress);
        return ip;
    }
}

From source file:org.mythtv.client.ui.MainMenuFragment.java

/**
 * @throws IOException/*from ww w .j a  v  a  2s.com*/
 */
private void startProbe() throws IOException {
    Log.v(TAG, "startProbe : enter");

    if (zeroConf != null) {
        stopProbe();
    }

    // figure out our wifi address, otherwise bail
    WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);

    WifiInfo wifiinfo = wifi.getConnectionInfo();
    int intaddr = wifiinfo.getIpAddress();

    byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
            (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
    InetAddress addr = InetAddress.getByAddress(byteaddr);
    Log.d(TAG, "startProbe : wifi address=" + addr.toString());

    // start multicast lock
    mLock = wifi.createMulticastLock("mythtv_lock");
    mLock.setReferenceCounted(true);
    mLock.acquire();

    zeroConf = JmDNS.create(addr, HOSTNAME);
    zeroConf.addServiceListener(MYTHTV_FRONTEND_TYPE, this);

    Log.v(TAG, "startProbe : exit");
}

From source file:com.entertailion.android.dial.ServerFinder.java

private boolean isWifiAvailable() {
    try {// w  ww. j a  v a 2 s.c  o  m
        if (isSimulator()) {
            return true;
        }
        if (!wifiManager.isWifiEnabled()) {
            return false;
        }
        WifiInfo info = wifiManager.getConnectionInfo();
        return info != null && info.getIpAddress() != 0;
    } catch (Exception e) {
        Log.e(LOG_TAG, "isWifiAvailable", e);
    }
    return false;
}

From source file:com.prey.PreyPhone.java

private void updateWifi() {
    wifi = new Wifi();
    try {/*from ww w  . jav a2  s.com*/
        WifiManager wifiMgr = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();

        wifi.setWifiEnabled(wifiMgr.isWifiEnabled());

        int ipAddress = wifiInfo.getIpAddress();
        wifi.setIpAddress(formatterIp(ipAddress));
        wifi.setMacAddress(wifiInfo.getMacAddress());
        DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
        wifi.setNetmask(formatterIp(dhcpInfo.netmask));
        wifi.setGatewayIp(formatterIp(dhcpInfo.serverAddress));
        if (ipAddress != 0) {
            wifi.setInterfaceType("Wireless");
        } else {
            if (PreyConnectivityManager.getInstance(ctx).isMobileConnected()) {
                wifi.setInterfaceType("Mobile");
            } else {
                wifi.setInterfaceType("");
            }
        }
        wifi.setName("eth0");
        String ssid = wifiInfo.getSSID();
        try {
            ssid = ssid.replaceAll("\"", "");
        } catch (Exception e) {

        }
        wifi.setSsid(ssid);

        for (int i = 0; listWifi != null && i < listWifi.size(); i++) {
            Wifi _wifi = listWifi.get(i);
            ssid = _wifi.getSsid();
            try {
                ssid = ssid.replaceAll("\"", "");
            } catch (Exception e) {

            }
            if (ssid.equals(wifi.getSsid())) {
                wifi.setSecurity(_wifi.getSecurity());
                wifi.setSignalStrength(_wifi.getSignalStrength());
                wifi.setChannel(_wifi.getChannel());
                break;
            }
        }
    } catch (Exception e) {
    }
}

From source file:com.willhauck.linconnectclient.SettingsActivity.java

@SuppressLint("SimpleDateFormat")
private void setupSimplePreferencesScreen() {
    // Load preferences
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);

    // Add preferences from XML
    addPreferencesFromResource(R.xml.pref_general);
    bindPreferenceSummaryToValue(findPreference("pref_ip"));

    // Preference Categories
    serverCategory = ((PreferenceCategory) findPreference("cat_servers"));

    // Preferences
    refreshPreference = ((Preference) findPreference("pref_refresh"));
    serverCategory.removePreference(refreshPreference);

    loadingPreference = ((Preference) findPreference("pref_loading"));
    serverCategory.removePreference(loadingPreference);

    Preference prefEnable = findPreference("pref_enable");
    prefEnable.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override/*from  w  w w .  j a  v a2 s  .  co m*/
        public boolean onPreferenceClick(Preference arg0) {
            // If Android 4.3+, open Notification Listener settings,
            // otherwise open accessibility settings
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                startActivityForResult(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS), 0);
            } else {
                Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
            }
            return true;
        }
    });

    ((Preference) findPreference("pref_ip")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference arg0, Object arg1) {
            // Update Custom IP address summary
            arg0.setSummary((String) arg1);

            refreshServerList();

            // Create and send test notification
            SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
            Object[] notif = new Object[3];
            notif[0] = "Hello from Android!";
            notif[1] = "Test succesful @ " + sf.format(new Date());
            notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);
            new TestTask().execute(notif);

            return true;
        }
    });

    Preference prefDownload = findPreference("pref_download");
    prefDownload.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Create share dialog with server download URL
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT,
                    "Download LinConnect server @ https://github.com/hauckwill/linconnect-server");
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
            return true;
        }
    });

    Preference prefApplication = findPreference("pref_application");
    prefApplication.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open application settings screen
            Intent intent = new Intent(getApplicationContext(), ApplicationSettingsActivity.class);

            startActivity(intent);
            return true;
        }
    });

    Preference prefDonateBitcoin = findPreference("pref_donate_btc");
    prefDonateBitcoin.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            try {
                // Open installed Bitcoin wallet if possible
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(
                        "bitcoin:1125MguyS1feaop99bCDPQG6ukUcMuvVBo?label=Will%20Hauck&message=Donation%20for%20LinConnect"));
                startActivity(intent);
            } catch (Exception e) {
                // Otherwise, show dialog with Bitcoin address
                EditText input = new EditText(SettingsActivity.this);
                input.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                input.setEnabled(false);

                new AlertDialog.Builder(SettingsActivity.this).setTitle("Bitcoin Address")
                        .setMessage(
                                "Please donate to the following Bitcoin address. Thank you for the support.")
                        .setView(input)
                        .setPositiveButton("Copy Address", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                        Context.CLIPBOARD_SERVICE);
                                clipboard.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                            }
                        }).setNegativeButton("Okay", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        }).show();
            }
            return true;
        }
    });

    Preference prefGooglePlus = findPreference("pref_google_plus");
    prefGooglePlus.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Google Plus page
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://plus.google.com/114633032648182423928/posts"));
            startActivity(intent);
            return true;
        }
    });

    Preference prefDonatePlay = findPreference("pref_donate_play");
    prefDonatePlay.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Donation Key app on Play Store
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=com.willhauck.donation"));
            startActivity(intent);
            return true;
        }
    });

    // Create handler to process a detected server
    serverFoundHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.obj != null) {

                javax.jmdns.ServiceInfo serviceInfo = mJmDNS.getServiceInfo(jmDnsServiceType, (String) msg.obj);

                // Get info about server
                String name = serviceInfo.getName();
                String port = String.valueOf(serviceInfo.getPort());
                String ip = serviceInfo.getHostAddresses()[0];

                // Create a preference representing the server
                Preference p = new Preference(SettingsActivity.this);
                p.setTitle(name);
                p.setSummary(ip + ":" + port);

                p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference arg0) {
                        refreshServerList();

                        // Save IP address in preferences
                        Editor e = sharedPreferences.edit();
                        e.putString("pref_ip", arg0.getSummary().toString());
                        e.apply();

                        // Create and send test notification
                        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");

                        Object[] notif = new Object[3];
                        notif[0] = "Hello from Android!";
                        notif[1] = "Test succesful @ " + sf.format(new Date());
                        notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);

                        new TestTask().execute(notif);

                        return true;
                    }

                });

                // Add preference to server list if it doesn't already exist
                boolean found = false;
                for (int i = 0; i < serverCategory.getPreferenceCount(); i++) {
                    if (serverCategory.getPreference(i) != null
                            && serverCategory.getPreference(i).getTitle() != null
                            && serverCategory.getPreference(i).getTitle().equals(p.getTitle())) {
                        found = true;
                    }
                }
                if (!found) {
                    serverCategory.addPreference(p);
                }

                refreshServerList();

                // Remove loading indicator, add refresh indicator if it
                // isn't already there
                if (findPreference("pref_loading") != null)
                    serverCategory.removePreference(findPreference("pref_loading"));
                if (findPreference("pref_refresh") == null)
                    serverCategory.addPreference(refreshPreference);

            }
            return true;
        }
    });

    // Create task to scan for servers
    class ServerScanTask extends AsyncTask<String, ServiceEvent, Boolean> {

        @Override
        protected void onPreExecute() {
            // Remove refresh preference, add loading preference
            if (findPreference("pref_refresh") != null)
                serverCategory.removePreference(refreshPreference);
            serverCategory.addPreference(loadingPreference);

            try {
                mJmDNS.removeServiceListener(jmDnsServiceType, ServerListener);
            } catch (Exception e) {
            }

            refreshServerList();

        }

        @Override
        protected Boolean doInBackground(String... notif) {
            WifiInfo wifiinfo = mWifiManager.getConnectionInfo();
            int intaddr = wifiinfo.getIpAddress();

            // Ensure there is an active Wifi connection
            if (intaddr != 0) {
                byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
                        (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
                InetAddress addr = null;
                try {
                    addr = InetAddress.getByAddress(byteaddr);
                } catch (UnknownHostException e1) {
                }

                // Create Multicast lock (required for JmDNS)
                mMulticastLock = mWifiManager.createMulticastLock("LinConnect");
                mMulticastLock.setReferenceCounted(true);
                mMulticastLock.acquire();

                try {
                    mJmDNS = JmDNS.create(addr, "LinConnect");
                } catch (IOException e) {
                }

                // Create listener for detected servers
                ServerListener = new ServiceListener() {

                    @Override
                    public void serviceAdded(ServiceEvent arg0) {
                        final String name = arg0.getName();
                        // Send the server data to the handler, delayed by
                        // 500ms to ensure all information is read
                        serverFoundHandler.sendMessageDelayed(Message.obtain(serverFoundHandler, -1, name),
                                500);
                    }

                    @Override
                    public void serviceRemoved(ServiceEvent arg0) {
                    }

                    @Override
                    public void serviceResolved(ServiceEvent arg0) {
                        mJmDNS.requestServiceInfo(arg0.getType(), arg0.getName(), 1);
                    }
                };
                mJmDNS.addServiceListener(jmDnsServiceType, ServerListener);

                return true;
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (!result) {
                // Notify user if there is no connection
                if (findPreference("pref_loading") != null) {
                    serverCategory.removePreference(findPreference("pref_loading"));
                    serverCategory.addPreference(refreshPreference);

                }
                Toast.makeText(getApplicationContext(), "Error: no connection.", Toast.LENGTH_LONG).show();
            }
        }
    }

    refreshPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference arg0) {
            new ServerScanTask().execute();
            return true;
        }

    });

    // Start scanning for servers
    new ServerScanTask().execute();
}

From source file:mobisocial.musubi.ui.NearbyActivity.java

private void doCheckin() {
    WifiInfo wifi = mWifiManager.getConnectionInfo();
    String myWifiName = wifi.getSSID();
    if (myWifiName == null) {
        /**//from  w w w .  j a  v a  2  s.  c  o m
         * TODO:
         * Depending on desired outcome, either help them get on wifi
         * or try connecting to gps server, etc.
         */
        toast("No wifi network available.");
        return;
    }

    String myWifiId = wifi.getBSSID();
    String myIp = formatIp(wifi.getIpAddress());
    String myWifiFingerprint = Util.computeWifiFingerprint(mWifiManager.getScanResults());

    if (DBG)
        Log.d(TAG, "Checking in to " + myWifiName + "...");
    JSONObject loc = new JSONObject();
    try {
        loc.put(DbContactAttributes.ATTR_WIFI_SSID, myWifiName);
        if (myWifiId != null) {
            loc.put(DbContactAttributes.ATTR_WIFI_BSSID, myWifiId);
        }
        if (myIp != null) {
            loc.put(DbContactAttributes.ATTR_LAN_IP, myIp);
        }
        loc.put(DbContactAttributes.ATTR_WIFI_FINGERPRINT, myWifiFingerprint);
    } catch (JSONException e) {
        // Impossible json exception
    }

    //XXX killed for now
    //mMusubi.getAppFeed().postObj(new MemObj("locUpdate", loc));
    //toast("Checked in to '" + myWifiName + "'.");
}