我的Android应用程序如何检测IP地址范围

时间:2014-07-10 06:25:22

标签: java android

我希望我的Android应用程序基本上检测一系列的IP地址,从192.168.150.0 - .255,我希望它将它放在void onStart中,我创建了一个数组,但它不起作用。

这是我主要活动的java类

MediaPlayer playMusic;

@Override    
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    for(int array;array < 256;array++)
    try {

        if("192.168.150")
    }            
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();

    //playMusic.release();
}

/**
 * Touch listener to use for in-layout UI controls to delay hiding the
 * system UI. This is to prevent the jarring behavior of controls going away
 * while interacting with activity UI.
 */
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (AUTO_HIDE) {
            delayedHide(AUTO_HIDE_DELAY_MILLIS);
        }
        return false;
    }
};

Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
    @Override
    public void run() {
        mSystemUiHider.hide();
    }
};

/**
 * Schedules a call to hide() in [delay] milliseconds, canceling any
 * previously scheduled calls.
 */
private void delayedHide(int delayMillis) {
    mHideHandler.removeCallbacks(mHideRunnable);
    mHideHandler.postDelayed(mHideRunnable, delayMillis);
}

}

这是我在应用程序打开时检测wifi的java类

public class WiFiChangeBroadcastReceiver extends BroadcastReceiver {
    private String LOGTAG = getClass().getSimpleName();

    @Override 
    public void onReceive(Context context, Intent intent) {
        Log.d(LOGTAG, "WiFi Status Changed");
        if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            NetworkInfo networkInfo = intent
                    .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (networkInfo.isConnected()) {
                Log.d(LOGTAG,
                        "Wifi is connected: " + String.valueOf(networkInfo));
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用此命令获取IP地址:

public String getIpAddr() {
   WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ip = wifiInfo.getIpAddress();

   String ipString = String.format(
   "%d.%d.%d.%d",
   (ip & 0xff),
   (ip >> 8 & 0xff),
   (ip >> 16 & 0xff),
   (ip >> 24 & 0xff));

   return ipString;
}

请注意:您需要在android.permission.INTERNET android.permission.ACCESS_WIFI_STATE中添加AndroidManifest.xml<user-permission/>以访问代码。

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

参考:https://stackoverflow.com/a/7975955/1239966