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.harshad.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//  w  w w .  j a  va  2 s  .  c  om
        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.ICE_CREAM_SANDWICH) {
                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:com.google.android.apps.tvremote.DeviceFinder.java

private boolean isWifiAvailable() {
    if (!wifiManager.isWifiEnabled()) {
        return false;
    }//  w w  w  . ja v a2s.  co  m
    WifiInfo info = wifiManager.getConnectionInfo();
    return info != null && info.getIpAddress() != 0;
}

From source file:com.mobilyzer.util.PhoneUtils.java

public String getWifiIpAddress() {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (wifiInfo != null) {
        int ip = wifiInfo.getIpAddress();
        if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
            ip = Integer.reverseBytes(ip);
        }/* w  ww  .j a va  2 s .  c o  m*/
        byte[] bytes = BigInteger.valueOf(ip).toByteArray();
        String address;
        try {
            address = InetAddress.getByAddress(bytes).getHostAddress();
            return address;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }
    return null;
}

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 w  w. ja  v a 2 s  .  com*/
    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;
}

From source file:org.sipdroid.sipua.ui.Receiver.java

@Override
public void onReceive(Context context, Intent intent) {
    String intentAction = intent.getAction();
    if (!Sipdroid.on(context))
        return;/*from   w  ww  .  jav a  2 s .c  o m*/
    if (!Sipdroid.release)
        Log.i("SipUA:", intentAction);
    if (mContext == null)
        mContext = context;
    if (intentAction.equals(Intent.ACTION_BOOT_COMPLETED)) {
        on_vpn(false);
        engine(context).register();
    } else if (intentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION)
            || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_AVAILABLE)
            || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)
            || intentAction.equals(Intent.ACTION_PACKAGE_REPLACED)) {
        engine(context).register();
    } else if (intentAction.equals(ACTION_VPN_CONNECTIVITY) && intent.hasExtra("connection_state")) {
        String state = intent.getSerializableExtra("connection_state").toString();
        if (state != null && on_vpn() != state.equals("CONNECTED")) {
            on_vpn(state.equals("CONNECTED"));
            for (SipProvider sip_provider : engine(context).sip_providers)
                if (sip_provider != null)
                    sip_provider.haltConnections();
            engine(context).register();
        }
    } else if (intentAction.equals(ACTION_DATA_STATE_CHANGED)) {
        engine(context).registerMore();
    } else if (intentAction.equals(ACTION_PHONE_STATE_CHANGED)
            && !intent.getBooleanExtra(context.getString(R.string.app_name), false)) {
        stopRingtone();
        pstn_state = intent.getStringExtra("state");
        pstn_time = SystemClock.elapsedRealtime();
        if (pstn_state.equals("IDLE") && call_state != UserAgent.UA_STATE_IDLE)
            broadcastCallStateChanged(null, null);
        if (!pstn_state.equals("IDLE") && call_state == UserAgent.UA_STATE_INCALL)
            mHandler.sendEmptyMessageDelayed(MSG_HOLD, 5000);
        else if (!pstn_state.equals("IDLE") && (call_state == UserAgent.UA_STATE_INCOMING_CALL
                || call_state == UserAgent.UA_STATE_OUTGOING_CALL))
            mHandler.sendEmptyMessageDelayed(MSG_HANGUP, 5000);
        else if (pstn_state.equals("IDLE")) {
            mHandler.removeMessages(MSG_HOLD);
            mHandler.removeMessages(MSG_HANGUP);
            if (call_state == UserAgent.UA_STATE_HOLD)
                mHandler.sendEmptyMessageDelayed(MSG_HOLD, 1000);
        }
    } else if (intentAction.equals(ACTION_DOCK_EVENT)) {
        docked = intent.getIntExtra(EXTRA_DOCK_STATE, -1) & 7;
        if (call_state == UserAgent.UA_STATE_INCALL)
            engine(mContext).speaker(speakermode());
    } else if (intentAction.equals(ACTION_SCO_AUDIO_STATE_CHANGED)) {
        bluetooth = intent.getIntExtra(EXTRA_SCO_AUDIO_STATE, -1);
        progress();
        RtpStreamSender.changed = true;
    } else if (intentAction.equals(Intent.ACTION_HEADSET_PLUG)) {
        headset = intent.getIntExtra("state", -1);
        if (call_state == UserAgent.UA_STATE_INCALL)
            engine(mContext).speaker(speakermode());
    } else if (intentAction.equals(Intent.ACTION_SCREEN_ON)) {
        if (!PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI))
            alarm(0, OwnWifi.class);
    } else if (intentAction.equals(Intent.ACTION_USER_PRESENT)) {
        mHandler.sendEmptyMessageDelayed(MSG_ENABLE, 3000);
    } else if (intentAction.equals(Intent.ACTION_SCREEN_OFF)) {
        if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI)) {
            WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wi = wm.getConnectionInfo();
            if (wm.getWifiState() != WifiManager.WIFI_STATE_ENABLED || wi == null
                    || wi.getSupplicantState() != SupplicantState.COMPLETED || wi.getIpAddress() == 0)
                alarm(2 * 60, OwnWifi.class);
            else
                alarm(15 * 60, OwnWifi.class);
        }
        if (SipdroidEngine.pwl != null)
            for (PowerManager.WakeLock pwl : SipdroidEngine.pwl)
                if (pwl != null && pwl.isHeld()) {
                    pwl.release();
                    pwl.acquire();
                }
    } else if (intentAction.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
        if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI,
                org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI))
            mHandler.sendEmptyMessageDelayed(MSG_SCAN, 3000);
    } else if (intentAction.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
        if (SystemClock.uptimeMillis() > lastscan + 45000
                && PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                        org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI,
                        org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI)) {
            WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wi = wm.getConnectionInfo();
            String activeSSID = null;
            if (wi != null)
                activeSSID = wi.getSSID();
            if (activeSSID != null && (activeSSID.length() == 0 || activeSSID.equals("0x")))
                activeSSID = null;
            List<ScanResult> mScanResults = wm.getScanResults();
            List<WifiConfiguration> configurations = wm.getConfiguredNetworks();
            if (configurations != null) {
                WifiConfiguration bestconfig = null, maxconfig = null, activeconfig = null;
                for (final WifiConfiguration config : configurations) {
                    if (maxconfig == null || config.priority > maxconfig.priority) {
                        maxconfig = config;
                    }
                    if (config.SSID != null
                            && (config.SSID.equals("\"" + activeSSID + "\"") || config.SSID.equals(activeSSID)))
                        activeconfig = config;
                }
                ScanResult bestscan = null, activescan = null;
                if (mScanResults != null)
                    for (final ScanResult scan : mScanResults) {
                        for (final WifiConfiguration config : configurations) {
                            if (config.SSID != null && config.SSID.equals("\"" + scan.SSID + "\"")) {
                                if (bestscan == null || scan.level > bestscan.level) {
                                    bestscan = scan;
                                    bestconfig = config;
                                }
                                if (config == activeconfig)
                                    activescan = scan;
                            }
                        }
                    }
                if (activescan != null)
                    System.out.println("debug wifi asu(active)" + asu(activescan));
                if (bestconfig != null && (activeconfig == null || bestconfig.priority != activeconfig.priority)
                        && asu(bestscan) > asu(activescan) * 1.5 &&
                        /* (activeSSID == null || activescan != null) && */ asu(bestscan) > 22) {
                    if (!Sipdroid.release)
                        Log.i("SipUA:", "changing to " + bestconfig.SSID);
                    if (activeSSID == null || !activeSSID.equals(bestscan.SSID))
                        wm.disconnect();
                    bestconfig.priority = maxconfig.priority + 1;
                    wm.updateNetwork(bestconfig);
                    wm.enableNetwork(bestconfig.networkId, true);
                    wm.saveConfiguration();
                    if (activeSSID == null || !activeSSID.equals(bestscan.SSID))
                        wm.reconnect();
                    lastscan = SystemClock.uptimeMillis();
                } else if (activescan != null && asu(activescan) < 15) {
                    wm.disconnect();
                    wm.disableNetwork(activeconfig.networkId);
                    wm.saveConfiguration();
                }
            }
        }
    }
}

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

private NetworkInterface getNetworkInterface() {
    if (!wifi.isWifiEnabled()) {
        Log.d(TAG, "wifi not enabled");
        return null;
    }//from  ww w  . j  av  a  2  s. c o  m
    switch (wifi.getWifiState()) {
    case WifiManager.WIFI_STATE_ENABLED:
        // OK
        break;
    case WifiManager.WIFI_STATE_ENABLING:
        Log.d(TAG, "Wifi enabling");
        return null;
    case WifiManager.WIFI_STATE_DISABLING:
    case WifiManager.WIFI_STATE_DISABLED:
        Log.d(TAG, "wifi disabled/disabling");
        return null;
    default:
        Log.d(TAG, "Wifi state unknown");
        return null;
    }
    // has address?
    WifiInfo info = wifi.getConnectionInfo();
    int ip = info.getIpAddress();
    if (ip == 0) {
        Log.d(TAG, "waiting for an IP address");
        return null;
    }

    NetworkInterface ni = DnsUtils.getNetworkInterface(ip);
    return ni;
}

From source file:com.wheelphone.remotemini.WheelphoneRemoteMini.java

private void displayIpAddress() {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo();
    if (info != null && info.getNetworkId() > -1) {
        int i = info.getIpAddress();
        String ip = String.format("%d.%d.%d.%d", i & 0xff, i >> 8 & 0xff, i >> 16 & 0xff, i >> 24 & 0xff);
        line1.setText("HTTP://");
        line1.append(ip);/* w  ww .  ja  v  a2 s. c o  m*/
        line1.append(":8080");
        line2.setText("RTSP://");
        line2.append(ip);
        line2.append(":8086");
        streamingState(0);
    } else {
        line1.setText("HTTP://xxx.xxx.xxx.xxx:8080");
        line2.setText("RTSP://xxx.xxx.xxx.xxx:8086");
        streamingState(2);
    }
}

From source file:org.deviceconnect.android.deviceplugin.irkit.IRKitManager.java

/**
 * ?./*from   w  w  w .  ja  v a  2  s.co  m*/
 * 
 * @param context 
 */
public synchronized void startDetection(final ContextWrapper context) {

    if (isDetecting()) {
        return;
    }

    mIsDetecting = true;
    init(context);

    WifiManager wifi = getWifiManager(context);
    mMultiLock = wifi.createMulticastLock(MULTI_CAST_LOCK_TAG);
    mMultiLock.setReferenceCounted(true);
    mMultiLock.acquire();

    WifiInfo info = wifi.getConnectionInfo();
    if (info != null) {
        mIpValue = info.getIpAddress();
    } else {
        mIpValue = 0;
    }

    new Thread(new Runnable() {

        @Override
        public void run() {
            synchronized (INSTANCE) {
                try {
                    if (mDNS != null || mIpValue == 0) {
                        mIsDetecting = false;
                        return;
                    }
                    InetAddress ia = parseIPAddress(mIpValue);
                    if (ia == null) {
                        mIsDetecting = false;
                        return;
                    }

                    mDNS = JmDNS.create(ia);
                    mDNS.addServiceListener(SERVICE_TYPE, mServiceListener);
                    mIsDetecting = true;

                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "start detection.");
                    }

                } catch (IOException e) {
                    if (BuildConfig.DEBUG) {
                        e.printStackTrace();
                    }
                    mIsDetecting = false;
                    mDNS = null;
                }
            }
        }
    }).start();
}